The simple factory mode returns one of several possible classes based on the provided data or parameters. The common points are a bit like polymorphism in Object-Oriented Programming. A base class has multiple Derived classes, in another calling program, the specific derived class of the base class is returned Based on the parameter. The returned value is of the base class type, because the base class reference can point to the object of the derived class, in addition, all these derived classes contain functions of the base class. That is to say, the derived classes have the same functions, but the functions may be implemented differently.
The following is just a demonstration of the simple factory mode, and the code is not too complex. Therefore, you can use the Submile Text tool.
How to Use blog post link ghost.
Assume that A is A base class, and AB and AC are derived from A's derived classes. In the XFactory class, the AB or AC class is returned based on the parameters provided to it, the instance of the class returned is not that important for programmers, because these classes have the same method. What programmers need to do is to directly call the method through the base class reference, you don't have to worry about which derived class is returned, because these classes have the same method, but they are implemented differently. How to decide which derived class to return depends on the factory design. This method can be a very complex function or a simple function.
Next we will use a simple addition, subtraction, multiplication, division calculator to understand and implement the simple factory model.
Step 1:Based on the small example above, I first create A base class
NumberA { ; NumberB { ; result =
Step 2: Create the derived class AB AC, that is, add, subtract, multiply, and divide the four Derived classes.
result = = .NumberA + result = = .NumberA - result = = .NumberA * result = (.NumberB == Exception(= .NumberA /
Step 3: Create XFactory to return AB and AC.
Operation CreateOperate(= = = = =
Step 4: start with an addition call:
Main(= OperationFactory.CreateOperate(==
The running result is
In this simple factory model, we actually use some object-oriented programming ideas.
Creating Operation is actually for the businessEncapsulation.
Then implement addition, subtraction, multiplication, division, and class capitalInheritanceOperation and rewrite the corresponding business logic.
If we add an algorithm root (sqrt) algorithm, we only need to add a new class that inherits Operation, and then add a branch to the simple factory class. Here we find that this isEasy to expand (loose coupling) and easy to maintain.