Factory Method: defines an interface used to create an object, so that the subclass decides to instantiate the class. The factory method delays the instantiation of a class to the Child class. Structure of factory method mode
Taking the big talk design model as an Example
// Lei Feng class LeiFeng {public void Sweep () {Console. writeLine ("sweep");} public void Wash () {Console. writeLine ("laundry");} public void BuyRice () {Console. writeLine (" Mi") ;}// class Undergraduate: LeiFeng {}// community Volunteer class Volunteer: leiFeng {} // Lei Feng factory interface ifacloud {LeiFeng CreateLeiFeng ();} // UndergraduateFactory: ifacloud {public LeiFeng CreateLeiFeng () {return new Undergraduate () ;}// community Volunteer factory class VolunteerFactory: ifacloud {public LeiFeng CreateLeiFeng () {return new Volunteer ();}} client code static void Main (string [] args) {// factory method mode IFactory factory = new UndergraduateFactory (); // to change to "community volunteers", modify LeiFeng student = factory. createLeiFeng (); student. buyRice (); student. sweep (); student. wash ();}
The following class diagram is used for programming, rather than for implementation.) The factory class is abstracted into an interface. This interface has only one method, that is, the factory method of the abstract component. Then, all the factories of specific pharmaceutical production classes will implement this interface, and such a simple factory model will become a factory with abstract factory interfaces and multiple specific object generation, in this way, we do not need to change the original factory when adding a function. We only need to add the function class and the corresponding factory class.