Factory methodMode factorymethod
The implementation of the factory method mode delays the creation of specific products into sub-classes, thus solving the problem that the simple factory mode is difficult to expand.
The simple factory class is decomposed into abstract base classes and several specific classes are as follows:
// Abstract Factory method "headquarters" class factorymethod public abstract class factorymethod {// return the Abstract Factory method creator public Abstract Food creator () of the target food object ();} // potatoesfactory public class potatoesfactory: factorymethod, a subclass of "headquarters" {// specific factory method for implementing functions creator public override food creator () {// return the new specific object return New Potatoes () ;}// another specific subclass of "headquarters" tomatoesfactory public class tomatoesfactory: factorymethod {public override food creator () {return New tomatoes ();}}
If you want to add new features or products, you can usePolymorphismTo easily complete the expansion.
In the factory method model, the factory class and the specific product class have a parallel hierarchical structure, and they correspond one to one.
That is to say, when adding a function, it needs to be added in pairs.
Note: In the factory method mode, each specific factory class only creates a single instance. To achieve plant diversification (one factory produces multiple instances), the abstract factory mode is required.