Public classCreatefactory { Public StaticIcreate Generatorcreate (stringcreatename) { Switch(createname) { Case "people": return Newpeople (); Case "Animal": return NewAnimal (); default: Throw Newnotimplementedexception (); } } } /// <summary> ///human implementation of factory interfaces/// </summary> Public classPeople:icreate {#regionIcreate Members Public stringCreate () {return "Create human"; } #endregion } /// <summary> ///Animal implements factory interface/// </summary> Public classAnimal:icreate {#regionIcreate Members Public stringCreate () {return "Creating Animals"; } #endregion } /// <summary> ///Simple Factory interface, return value type/// </summary> Public Interfaceicreate {stringCreate (); }View Code
Simple factory: Returns an instance of a class based on the data supplied to it, usually the class it returns has a common parent class (or interface object)
The core of a simple factory is an instantiated object, a simple factory-instantiated class with the same interface or base class, in which the subclasses are relatively fixed and do not need to be extended, can use a simple factory,
The advantage of a simple factory is that it can obtain the corresponding instance according to the parameters, avoids the direct instantiation, reduces the coupling,
The disadvantage is that the types that can be instantiated are already determined during compilation, and if you add new types, you need to modify the factory, not the OCP (open and close principle), the simple factory needs to know all the types to be generated, when there are too many subclasses, or too many sub-levels are not suitable for simple factory use
Call:
Createfactory.generatorcreate ("people"). Create ()
2 Simple Factory mode