软件设计目标—基于简单工厂模式的计算器程序

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中增加分支。

所以,基于简单工厂模式的计算器程序,实现了部分开—闭原则。

相关文章
相关标签/搜索