The simple factory mode mainly uses the class polymorphism to create the corresponding subclass in the factory according to different requirements for different results.
A class chart with a simple calculator as an Example
The implementation of the operationfactory class in the figure is roughly as follows:
1 class operationfactory
2 {
3 public:
4 operation * createoperation (STD: String operator)
5 {
6 operation * poper = NULL;
7 switch (operator)
8 {
9 case '+ ':
10 poper = new operationadd;
11 break;
12 case '-':
13 poper = new operationsub;
14 break;
15 case '*':
16 poper = new operationmul;
17 break;
18 case '/':
19 poper = new operationdiv;
20 break;
21}
22 return poper;
23}
24 };
Call the getresult () method based on the returned pointer to obtain the result.
To add other operations, you only need to create a new operation class to implement the operation interface, and then add a case in the factory to instantiate the object.