1. 程式人生 > >軟體設計目標—基於簡單工廠模式的計算器程式

軟體設計目標—基於簡單工廠模式的計算器程式

interface Operation{
    public int getResult(int numberA, int numberB);
}

class OperationAdd implements Operation{
public int getResult(int numberA, int numberB){
          return numberA + numberB;
        }
}

class OperationSub implements Operation{
	public int getResult(int numberA, int numberB){
		return numberA - numberB;
	}
}

class OperationMul implements Operation{
	public int getResult(int numberA, int numberB){
		return numberA * numberB;
	}
}

class OperationDiv implements Operation{
	public int getResult(int numberA, int numberB){
		int result = 0;
		if (numberB!=0) 
			result = numberA / numberB;
		else{
			System.out.println("除數不能為0。");
			System.exit(0);
		}
		return result;
	}
}

class OperationFactory{
    public Operation createOperate(char operate){
      Operation oper = null;
      switch (operate){
      case '+':
    	  oper = new OperationAdd();
    	  break;
      case '-':
    	  oper = new OperationSub();
    	  break;
      case '*':
    	  oper = new OperationMul();
    	  break;
      case '/':
    	  oper = new OperationDiv();
    	  break;
      }
      return oper; 
    }
}

import java.io.*;
class clientSimpleFactory{
	public static void main(String[] args){
		int intNumberA=0, intNumberB=0;
		try{
			BufferedReader bufR = new BufferedReader( new InputStreamReader(System.in));
			System.out.print("請輸入數字A:");
			try{
				intNumberA = new Integer(bufR.readLine()).intValue();
			}catch(Exception e){
				System.out.println(e);
				System.exit(0);
			} 
			System.out.print("請輸入數字B:");
			try{
				intNumberB = new Integer(bufR.readLine()).intValue();
			}catch(Exception e){
				System.out.println(e);
				System.exit(0);
			} 
			Operation oper = new OperationFactory().createOperate('+');
			int result = oper.getResult(intNumberA, intNumberB);
			System.out.println("result = "+result);
		}catch(Exception e){
			System.out.println(e);
		}
	}
}


執行結果:

分析:

如果更改加法運算只需要修改OperationAdd即可。如果需要增加其他運算,只需增加相應的運運算元類。

但還需要修改運算類工廠,在switch中增加分支。

所以,基於簡單工廠模式的計算器程式,實現了部分開—閉原則。