When writing a calculator program, you can separate the business logic from the display, and the business logic is encapsulated into a class (encapsulation); if you want to add a new operation, you can first create a base class of Operation, and then various operations are inherited from the Operation class and implement the GetResult() virtual function. At this time, adding a new operation only requires a new class, that is, no previous operations are required to participate in the compilation. How do I let the calculator know which operation I want to use? A separate class should be considered to do this process of creating instances, and that's the factory. Create an OperationFactory class, pass in parameters, and the function createOperate can instantiate the appropriate object.
The Java code is as follows:
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 operation){ Operation operator = null; if (operate.equals("+")) { operator = new OperationAdd(); } else if (operate.equals("-")) { operator = new OperationSub(); } return operator; } public static void main(String[] args) { Operation operator; operator = OperationFactory.createOperate("+"); operator.set_numberA(1); operator.set_numberB(2); double result = operator.GetResult(); }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.