1. Factory Method Mode
The first is an interface for creating an object, letting the subclass decide which class to instantiate. The factory method defers the instantiation of a class to its subclasses.
* Factory method mode overcomes the disadvantage of the simple Factory mode violating the open-closed principle, and preserves the advantages of the encapsulation object creation process.
2. Example
namespaceFactory method Mode {classProgram {Static voidMain (string[] args) {Ifactory Factory=Newcundergraduate (); Leifeng Student=Factory. Createleifeng (); Student. Sweep (); Student. Wash (); Student. Buyrice (); Console.ReadLine (); } } /// <summary> ///classes of operations performed by public in all factories/// </summary> classLeifeng { Public voidSweep () {Console.WriteLine ("sweeping"); } Public voidWash () {Console.WriteLine ("Laundry"); } Public voidBuyrice () {Console.WriteLine ("Buy Rice"); } } /// <summary> ///Create a factory interface/// </summary> Interfaceifactory {Leifeng Createleifeng (); } /// <summary> ///classes that the factory needs to instantiate/// </summary> classUndergraduate:leifeng {}/// <summary> ///classes that the factory needs to instantiate/// </summary> classVoluteers:leifeng {}/// <summary> ///factory, used to instantiate classes/// </summary> classCundergraduate:ifactory { PublicLeifeng Createleifeng () {return NewUndergraduate (); } } /// <summary> ///factory, used to instantiate classes/// </summary> classCvoluteers:ifactory { PublicLeifeng Createleifeng () {return Newvoluteers (); } }}
(C #) Factory method mode