时间:2021-01-14 11:12:43 | 栏目:JAVA代码 | 点击:次
在编写一个计算器程序时,可以将业务逻辑和显示分离,业务逻辑封装为一个类(封装);如果要新添加一种运算,可以先创建一个Operation的基类,然后各种运算从Operation类继承,并实现GetResult()虚函数,这时添加新的运算只需要派生一个新的类,即不需要之前的运算参与编译。如何让计算器知道我是希望使用哪种运算呢?应该考虑单独的类来做这个创造实例的过程,这就是工厂。创建一个OperationFactory类,传入参数,函数createOperate就可以实例化出合适的对象。
Java代码如下:
public class OperationFactory { public static abstract class Operation { private double _numberA = 0; private double _numberB = 0; public double get_numberA() { return _numberA; } public void set_numberA(double _numberA) { this._numberA = _numberA; } public double get_numberB() { return _numberB; } public void set_numberB(double _numberB) { this._numberB = _numberB; } abstract double GetResult(); // TODO Auto-generated constructor stub } public static class OperationAdd extends Operation { double GetResult() { double result = get_numberA() + get_numberB(); return result; } } public static class OperationSub extends Operation { double GetResult() { double result = get_numberA() - get_numberB(); return result; } } public static Operation createOperate(String operate){ Operation oper = null; if (operate.equals("+")) { oper = new OperationAdd(); } else if (operate.equals("-")) { oper = new OperationSub(); } return oper; } public static void main(String[] args) { Operation oper; oper = OperationFactory.createOperate("+"); oper.set_numberA(1); oper.set_numberB(2); double result = oper.GetResult(); } }