Chapter 4 factory method mode

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.