1. Simple Description
The factory model has a very vivid description. The class of the object to be created is like a factory, and the object to be created is a product. The person who processes the product in the factory and uses the product, you don't have to worry about how the product is produced. From the perspective of software development, this effectively reduces the coupling between modules.
Ii. Category chart
Ii. Applicable scenarios
- In a program, there are many objects to be created, resulting in many new operations and complex operations on the object, you need to use the simple factory mode;
- Because we do not need to care about the object creation process, but focus on the actual operations of the object, we need to separate the creation and operation of the object, convenience for later program expansion and maintenance.
Iii. Code
1 # include <iostream> 2 class calculator {3 Public: 4 calculator (): number1 (0), number2 (0) {} 5 calculator (INT N1, int N2 ): number1 (N1), number2 (N2) {} 6 virtual ~ Calculator () {} 7 virtual int getresult () {return 0;} 8 virtual void setnumber1 (int n) {number1 = N;} 9 virtual void setnumber2 (int n) {number2 = N;} 10 protected: 11 int number1; 12 INT number2; 13}; 14 15 16 class Add: Public calculator {17 public: 18 virtual int getresult () {19 Return number1 + number2; 20} 21}; 22 23 class plus: Public calculator {24 public: 25 // For the sake of simplicity, it is no longer necessary to determine whether number1> number2, default number1> number226 virtual int getresult () {27 return number1-number2; 28} 29}; 30 31 Enum signal {32 _ add, 33 _ plus34 }; 35 36 class calculatorfactory {37 public: 38 calculator * getoperator (signal S) {39 switch (s) {40 case _ add: 41 calculator = new add (); // remember to release the pointer 42 break; 43 case _ plus: 44 calculator = new Plus (); 45 break; 46} 47 return calculator; 48} 49 private: 50 calculator * calculator; // the pointer or reference must be used here, otherwise the polymorphism 51} cannot be implemented; 52 53 int main () 54 {55 calculator * Cal = calculatorfactory (). getoperator (_ add); 56 cal-> setnumber1 (10); 57 cal-> setnumber2 (5); 58 STD: cout <"Calculator: "<cal-> getresult () <STD: Endl; 59 Delete Cal; 60 return 0; 61}
Design Mode 1-simple factory Mode