Design Model learning-factory method model

Source: Internet
Author: User

Factory method mode

GOOD: fixed the failure to comply with the open-closed principle in the simple factory model.

The factory method mode moves the selection and judgment to the client for implementation. If you want to add new features, you do not need to modify the original class and directly modify the client.

 

Example:

# Include <string>
# Include <iostream>
Using namespace std;
// Instance base class, equivalent to Product (for convenience, no abstraction is used)
Class LeiFeng
{
Public:
Virtual void Sweep ()
{
Cout <"Lei Feng sweeping thunder" <endl;
}
};

// A college student studying Lei Feng, equivalent to ConcreteProduct
Class Student: public LeiFeng
{
Public:
Virtual void Sweep ()
{
Cout <"college student sweeping" <endl;
}
};

// Volunteers from Lei Feng, equivalent to ConcreteProduct
Class Volenter: public LeiFeng
{
Public:
Virtual void Sweep ()
{
Cout <"Volunteers are abducted" <endl;
}
};
// Workshop-based Creator
Class LeiFengFactory
{
Public:
Virtual LeiFeng * CreateLeiFeng ()
{
Return new LeiFeng ();
}
};
// Workshop type
Class StudentFactory: public LeiFengFactory
{
Public:
Virtual LeiFeng * CreateLeiFeng ()
{
Return new Student ();
}
};
Class VolenterFactory: public LeiFengFactory
{
Public:
Virtual LeiFeng * CreateLeiFeng ()
{
Return new Volenter ();
}
};
// Client
Int main ()
{
LeiFengFactory * sf = new LeiFengFactory ();
LeiFeng * s = sf-> CreateLeiFeng ();
S-> Sweep ();
Delete s;
Delete sf;
Return 0;
}

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.