When writing a calculator program, you can separate the business logic from the display, and the business logic is encapsulated as a class (encapsulation); If you want to add a new operation, you can create a operation base class first, and then the various operations inherit from the Operation class and implement the GetResult () virtual function, Adding a new operation just needs to derive a new class that does not require previous operations to participate in the compilation. How do I get the calculator to know what kind of arithmetic I want to use? Separate classes should be considered to do the process of creating the instance, which is the factory. Create a Operationfactory class, pass in parameters, 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;
The public void Set_numbera (double _numbera) {This._numbera = _numbera;
Public double Get_numberb () {return _numberb;
The 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 ();
}
}
The above is the Java design pattern of the simple factory model of the whole content, I hope to help you learn, but also hope that we support cloud Habitat Community Network.