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.