We create different objects with Factory.
For example, if you create an interface for a car, create an object that implements the interface through the Factory factory, and create different objects based on our choices.
Create a car interface
/// <summary> /// Simple Factory mode /// </summary> Public Interface Iautocarmake { //<summary> /// Create a car /// </summary> void Createautocar (); }
Create two derived classes, respectively, to create two types of cars with different colors
/// <summary> ///Red Car/// </summary> Public class_redcar:iautocarmake { Public voidCreateautocar () {Console.WriteLine ("Create a red car"); } } /// <summary> ///Blue Car/// </summary> Public class_bluecar:iautocarmake { Public voidCreateautocar () {Console.WriteLine ("Create a blue car"); } }
Generating different object instances from the factory class
/// <summary> ///Simple Factory mode-factory class/// </summary> Public classFactory { PublicIautocarmake Createautocar (stringflag) { Switch(flag) { Case "Red": return New_redcar (); Case "Blue": return New_bluecar (); } return NULL; } Static voidMain (string[] args) {Iautocarmake Parents=NewFactory (). Createautocar ("Red"); Iautocarmake Parents=NewFactory (). Createautocar ("Blue"); Parents. Createautocar (); Console.readkey (); } }
C # design mode (2)--Simple Factory mode (Factory)