Design Mode Study Notes-factory method mode
I have learned the simple factory model and feel very useful. When creating an object, you can separate complex initialization operations from the client to simplify the client code. This greatly reduces the difficulty of code modification. In addition, different parameters can be used to create different objects.
However, the simple factory model has some drawbacks and violates the open-closed principle. That is, if we add a product, the corresponding factory also needs to be modified, that is, some new branch conditions should be added in switch --- case, which is not conducive to expansion. So we have the following factory method mode:
Factory method mode: defines an interface used to create objects. The subclass determines which class to instantiate. The factory method mode delays the instantiation of a class to the subclass.
// Design mode Demo. cpp: defines the entry point of the console application. // # Include "stdafx. h" # include
# Include
Using namespace std; // The created object base 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! "<
Create ()-> func (); // Create a bird factory god = new BirdFactory (); // generate a bird object and execute the action god-> Create () -> func (); getchar (); return 0 ;}
Result:
I am a human. I can walk!
I am a bird. I can fly!
When using the factory method mode, when we define a factory method, we only need to define an interface or abstract class. The subclass inherits the interface or abstract class, and the specific implementation is implemented by the subclass. Unlike the simple factory mode, you need to add judgment conditions in the factory. Here, the production method for adding subclass only needs to generate a related sub-factory class from the interface or abstract class. Follow the open-closed principle.