Here we will talk about the application of the factory model.
The factory mode mainly provides a transitional interface for creating objects, so that the specific process of creating objects is blocked and isolated to improve flexibility. This is also the technology of separation of objects and processes. The oo idea is introduced.
Generally, we divide the factory model into three types:
1) simple factory)
2) Factory method)
3) Abstract Factory mode (Abstract Factory)
Simple factory mode: simple factory mode is also called static factory method mode. Its purpose is to define an interface for creating objects.
Its composition:
Factory role: this is the core of this model and contains some commercial logic and judgment logic.
Abstract Product role: it is generally the parent class or implemented interface inherited by a specific product.
Specific product role: the object created by the factory class is the instance of this role. The implementation of the specific class is the actual function of the product.
The following is an example. I believe many people have read it:
A decade ago, he had three cars in his house, Benz, BMW, Audi, and hired a driver to drive for him. However, it is always strange for the nouveau riche to take a taxi: the Benz car was followed by the driver and said, "drive a taxi !", When he got on BMW, he said, "kaibao carriage !", Get on with Audi and say, "Drive on AUDI !". You must say: this person is ill! Just say you can't drive ?!
When we put the act of this nouveau riche into our program design, we will find that this is a common phenomenon. Fortunately, this disease can be avoided in OO (Object-Oriented) languages. Next we will introduce the topic of this article based on the C # Language: The Factory method of the factory model.
// Abstract Product role
Public interface car
{
String drive ();
}
// Specific product roles and implementation of specific classes
Public class benzcar: Car
{
Public String drive ()
{
Return "Driving Benz ";
}
}
Public class bmwcar: Car
{
Public String drive ()
{
Return "Driving BMW ";
}
}
// Factory role. The core of this model is physical factory.
Public static car drivercar (string category)
{
Switch (category)
{
Case "Benz ":
Return new benzcar ();
Break;
Case "bmwcar ":
Return new bmwcar ();
Break;
Default: return NULL;
}
}
// Here, the user only needs to choose the car to drive.
Protected void page_load (Object sender, eventargs E)
{
Car car = driver. drivercar ("Benz ");
Response. Write (car. Drive ());
}
The factory part does not seem ideal, because every time a car is added, the corresponding business logic or judgment logic must be added to the factory class. Abstract Factory patterns can change this. This can also be achieved through conditional external (configured in Web. config) and reflection (loaded object products ).