Factory mode, instantiating objects, replacing new operations with factory methods.
The factory model is basically the same as the simple factory model, where each addition of a subclass in a simple factory must add a judgment branch to the factory class, which violates the open/closed principle. The solution to the factory model is to generate a factory subclass for each judgment 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 modify the interface, only modify the implementation, then the factory sub-class is the implementation, Tim Machining class and its code does not modify the abstract interface, that is, the principle of opening and closing.
The disadvantage is that after more products, to maintain the amount of increased, there will be a lot of factory sub-class, although the work factory class only to create products. Not adding a product will add a factory sub-category, increase the workload.
Factory mode is just a little bit of optimization in a simple factory, so it 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