Design Model Series-simple factory

Source: Internet
Author: User

Design Model Series-simple factory learning Android and jav programming knowledge during this time
Taking this opportunity, I will summarize the design patterns I have learned and used, and write them down using java

Simple factory first
A simple factory is one of the factory models, but it does not seem to be listed in the GOF model.
One sentence: A simple factory is to generate a given object according to the given requirements.
The simple java version code is as follows:
Public interface Product
{
Abstract public void Call ();
};

Public Pen implements Product
{
Public void Call ()
{

}
};

Public Book implements Product
{
Public void Call ()
{

}
};


Public clas Factory
{
Public Product CreateProducrt (String name)
{
If (name. equals ("Pen "))
Return Pen. class. newInstance ();
Else if (name. equals ("Book "))
Return Book. class. newInstance ();
Return null;
}
};

 


A simple factory is to return a given object instance based on the input tag.

Obviously, the main defect of a simple factory is that if you want to add a new product, you need to modify its product generation function.

In addition, if the factory and product objects are combined into one, the form is as follows:
Public class Object
{
Public static ObjectCreateObject (String name );
Other function.
}; This is similar to CObject in MFC

An example of a simple factory is as follows (I previously wrote the GUI ):
Class WidgetFactory
{
Public:
Widget * CreateWidgetByName (const std: string & name );
}; Here, if Spin is input, a new Spin is returned. If a Slider is input, a new Slider object is returned.
If I add a new Widget Object, I need to modify the CreateWidgetByName function (of course, the Object: CreateObject (name) function can be used, but only the returned Object needs to undergo type conversion. The principles are the same)

Next, let's talk about abstract factory and factory methods.

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.