Factory mode, instantiating objects, replacing new operations with factory methods.
The factory model is almost identical to the simple factory model, where each addition of a subclass in a simple factory must include an inferred branch in the factory class, which violates the open/closed principle. The solution to the factory model is to generate a factory subclass for each inference in a simple factory, where the factory subclass is located between the factory class abstraction and the product class implementation, and the actual implementation is still true. Factory class for the abstract interface, open and close principle or change the interface, just change the implementation, then the factory sub-class is implemented, adding factory sub-class and its code does not change the abstract interface, that is, to achieve the open and closed principle.
The disadvantage is that after more products, to maintain the amount of added, there will be a lot of factory sub-class, although the factory sub-class only to create products work. Without adding a product, add a factory subclass and add a workload.
The factory model is just a little optimization of the Simple factory, which follows the open and closed principle. The application scenario is similar to a simple factory, where there are not many subclasses.
Simple implementation of the factory model:
Class bass{public:virtual void fun () = 0;bass () {}virtual ~bass () {}};class a:public bass{public:virtual void Fun () {COUT&L t;< "A" <<ENDL;} A () {}virtual ~a () {}};class b:public bass{public:virtual void Fun () {cout<< "B" <<ENDL;} B () {}virtual ~b () {}};class abstractfactory{public:abstractfactory () {};virtual ~abstractfactory (); Virtual bass* Createproduct () = 0;}; Class Factorya:public Abstractfactory{factorya () {}~factorya () {}a* createproduct () {return new A ();}}; Class Factoryb:public Abstractfactory{public:factoryb () {}~factoryb () {}b* createproduct () {return new B ();}};
C + + implementation of design Patterns 2. Factory mode