Purpose:
Defines an interface used to create objects, so that the subclass determines which class to instantiate. Factory method delays the instantiation of a class to its subclass.
UML structure diagram:
Abstract base class:
1) product: the abstract base class of the created object.
2) The factory creates an abstract base class for the factory method of the object.
Interface functions:
1) Creator: factorymethod: pure virtual function, which is implemented by the derived class to create the corresponding product.
Resolution:
In this mode, there are two abstract base classes. One is the abstract base class of the object created by product, and the other is the factory abstract base class, when collaborating with each other, the product derived class is generated by the corresponding factory derived class. That is to say, if you want to add a product, you also need to add a factory, the creation process is delegated to this factory. that is to say, a factory corresponds to a product one by one.
Note:
In the demo diagram of the design mode, the factory class is named creator. The following implementation follows the naming convention.
Personal opinion: the main part of the core is a specific class. When a Factory receives a request to automatically determine the product to provide, but for a factory, if a new product is added, too many changes are required. In other words, to add a new product, the entire factory must be changed.
# Include <iostream> <br/> using namespace STD; <br/> class product <br/>{< br/> Public: <br/> virtual void produce () {}; // The specific implementation is handed over to the subclass function; <br/> virtual void complete () {}; <br/> product (){}; <br/> virtual ~ Product () {}; <br/>}; <br/> class conproduct1: public product <br/>{< br/> Public: <br/> void produce () <br/> {cout <"Pro conproduct1 .. "<Endl ;}< br/> void Merge () <br/> {cout <" sel conproduct1 .. "<Endl ;}< br/>}; <br/> class conproduct2: public product <br/>{< br/> Public: <br/> void produce () <br/> {cout <"Pro conproduct2 .. "<Endl ;}< br/> void Merge () <br/> {cout <" sel conproduct2 .. "<Endl ;}< br/>}; <br/> class factory // the specific operation is controlled by the factory and selected <br/>{< br/> public: <br/> Factory () {}< br/> static product * creatproduct (int A) <br/>{< br/> if (a = 1) {return New conproduct1 () ;}// generate the corresponding pro object; <br/> if (a = 2) {return New conproduct2 ();} <br/>}< br/>}; <br/> void main () <br/>{< br/> factory * FAC = new factory (); <br/> (fac-> creatproduct (2)-> produce (); <br/>}