Design Mode Study Notes-simple factory Mode
Background:
During the development process, a large number of objects are often created, and a series of initialization operations are involved after the object is created, and we do not necessarily just use the object immediately after the object is created, in addition, if the initialization operation is complex, the code looks messy. If there is a change, all the initialization operations must be modified, which is quite difficult to maintain.
Function:
Separate object creation and use for object creation and initialization. After extension, you can create different objects based on different parameters.
Example:
// Design mode Demo. cpp: defines the entry point of the console application. // # Include "stdafx. h" # include
# Include
Using namespace std; // The base class Product of the created object {protected: int num; string name; public: void setNum (int n) {num = n ;} void setName (string na) {name = na;} virtual void show () = 0 ;}; // subclass 1 class Product1: public Product {void show () {cout <"Product1 num:" <
<<" 1:="" 2="" :="" case="" int="" name:="" num:="" product="" product-="" product2="" public="" public:="" simplefactory="" static="" string="" switch="" void="">
SetNum (num); product-> setName (name); return product;} case 2: {Product * product = new Product2 (); product-> setNum (num ); product-> setName (name); return product;} default: return NULL ;}}; int _ tmain (int argc, _ TCHAR * argv []) {SimpleFactory factory; product * product = factory. getProduct (1, 0, "hehe"); product-> show (); product = factory. getProduct (2, 1, "haha"); product-> show (); getchar (); return 0 ;}
<<">
Result:
Product1 num: 0 name: hehe
Product2 num: 1 name: haha
It can be seen that after the simple factory mode is used, the code for creating an object becomes very simple. You only need to make some modifications within the factory class, instead of having to do the same as before, each time an object is created, it must be modified. Greatly increased the simplicity of the Code.