Learn simple Factory mode, feel very useful. When you create an object, you can detach complex initialization operations from the client and simplify the client code. Greatly reduces the difficulty of code modification. And you can create different objects by using different parameters.
But the simple factory model also has some drawbacks that violate the open-closure principle. That is, if we add a product, the corresponding factory will also be modified, that is, switch---case to add some new branch conditions, not conducive to expansion. So we have the following factory method mode:
Factory method Mode: Defines an interface for creating objects, subclasses decide which class to instantiate, and the factory method pattern defers the instantiation of a class to subclasses.
Design pattern Demo.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <string>using namespace std;//created object base class animal class animal{ public:virtual void func () = 0;};/ /Subclass Bird Class Bird:public animal{public:void func () override{cout<< "I am a Bird. I can fly! " <<endl;}};/ /Subclass Human Class Human:public animal{public:void func () override{cout<< "I am a Human. I can walk! " <<endl;}};/ /factory base class Factorymethod{public:virtual animal* Create () = 0;};/ /Human factory class Humanfactory:public factorymethod{public:animal* Create () Override{return new Human ();}};/ /Bird Factory class Birdfactory:public factorymethod{public:animal* Create () Override{return new Bird ();}; int _tmain (int argc, _tchar* argv[]) {//Create a human factory factorymethod* God = new Humanfactory ();//Generate human objects and perform operations God->create ()- >func ();//Create a bird factory god = new Birdfactory ();//Generate Bird objects and perform operations God->create ()->func (); GetChar (); return 0;} <strong></strong>
Results:
I am a human. I can walk!
I am a bird. I can fly!
When using the factory method pattern, when we define a factory method, as long as we define an interface or abstract class, the subclass inherits the interface or abstract class, and the implementation is implemented by subclasses. And unlike the simple factory model, there is a need to add judgment to the factory, where the production method of the subclass is added, and only a related sub-factory class is derived from the interface or abstract class. Follow the open-closed principle.
Design Pattern Learning Notes-factory method mode