The factory model is basically the same as the simple factory model, in a simple factory, each time a product subclass is added a judgment branch must be added to the factory class, which violates the open-closed principle, so the factory pattern is created to solve the problem.
Since every time you have to judge, then I will make these judgments to create a factory subclass, so that every time you add a product subclass, just add a factory subclass. This is perfectly followed by the open-close principle. But there are problems, if the number of products enough, to maintain the amount will increase, fortunately, the General Factory sub-class is only used to generate product classes, as long as the name of the product subclass does not change, then the basic factory sub-class will not need to modify, each time only need to modify the product subclass can be.
The same factory model generally should use only one of the products in most parts of the program, and the factory class does not have to create product classes frequently. This changes only need to modify a limited number of places.
Code implementation:
#include <iostream> #include <string>using namespace std;class fruit{public:virtual void Sayname () { cout<< "Fruit" <<endl; }};class banana:public fruit{public:virtual void Sayname () {cout<< "I'm a banana! "<<endl; }};class pear:public fruit{public:virtual void Sayname () {cout<< "I'm a pear!" "<<endl; }};class fruitfactory{public:virtual Fruit *getfruit () {cout<< "Fruitfactory::getfruit" <<endl; return nullptr; }};class bananafactory:public fruitfactory{public:virtual Fruit *getfruit () {return new Banana; }};class pearfactory:public fruitfactory{public:virtual Fruit *getfruit () {return new Pear; }};int Main () {fruitfactory *ff = nullptr; Fruit *fruit = nullptr; Banana FF = new Bananafactory; Fruit = Ff->getfruit (); Fruit->sayname (); Delete fruit; Delete ff; Pear ff = new Pearfactory; Fruit = Ff->getfruit (); Fruit->sayname (); Delete fruit; Delete ff; return 0;}
Operation Result:
Design mode-Factory mode