Factory method mode:
Defines an interface for a user to create an object, so that the subclass decides which class to instantiate. The factory method delays the instantiation of a class to its subclass.
When the factory method mode is implemented, the client needs to decide which factory to instantiate to implement the computing class, and select whether the problem still exists. That is to say,
The factory method is simple. The internal logic judgment of the factory is moved to the client code. If you want to add a function, you have to change the factory class, but now you want to modify the client.
/// <Summary> // Lei Feng // </Summary> public class Leifeng {public void wash () {console. writeline ("laundry");} public void sweep () {console. writeline ("sweep") ;}/// <summary >/// college student /// </Summary> public class undergraduate: leifeng {}/// <summary> // community volunteer /// </Summary> public class communityvolunteer: leifeng {} // <summary> // Lei Feng factory // </Summary> interface ifacloud {Leifeng createleifeng ();} /// <summary> // /// </Summary> public class undergraduatefactory: ifactory {public Leifeng createleifeng () {return New Undergraduate ();}} /// <summary> // community volunteer Lei Feng factory // </Summary> public class communityvolunteerfactory: ifacloud {public Leifeng createleifeng () {return New communityvolunteer ();}}
Client call
IFactory factory = new UndergraduateFactory();LeiFeng leifeng = factory.CreateLeiFeng();leifeng.Sweep();leifeng.Wash();factory = new CommunityVolunteerFactory();leifeng = factory.CreateLeiFeng();leifeng.Sweep();leifeng.Wash();
Result
Chapter 4 factory method mode