Implementation of the simple factory mode.
Assume that myProgramContains a series of objects, such as bed, desk, Chair ..., To use them, we must generate them in the program based on user requirements and call the new operator one by one, so that the client program will know the information of the corresponding class and generateCodeObviously not flexible enough. They are obviously a type of furniture. In this case, we only need a factory that produces furniture. instead of using specific classes in the code, we can simply describe what we need and then get the desired object.
First define a class, mainly declare a furniture interface, bed and chair class:
Public Interface Ifurniture
{}
Public Class Bed: ifurniture
{
Public Bed ()
{
Console. writeline ( " I need a bed! " );
}
}
Public Class Desk: ifurniture
{
Public Desk ()
{
Console. writeline ( " I need a desk! " );
}
}
Public Class Chair: ifurniture
{
Public Chair ()
{
Console. writeline ( " I need a chair! " );
}
}
Define a furniture factory class (you can use the type class in the reflection mechanism to obtain the type information of the class name specified by name, and then use system. activator to create an object based on this information ):
Public Class Furniturefactory
{
Public Ifurniture makefurniture ( String Name)
{
Ifurniture myfurniture = Null ;
Try
{
Type type = Type. GetType (name, True );
Myfurniture = (Ifurniture) activator. createinstance (type );
}
Catch (Typeloadexception E)
Console. writeline ( " I dont know this kind of furniture,
Exception caught - { 0 } " , E. Message );
Return Myfurniture;
}
}
Then the program is called on the client:
String Furniturename = Console. Readline ();
Ifurniture myfurniture;
Furniturefactory myfurniturefactory = New Furniturefactory ();
Myfurniture = Myfurniturefactory. makefurniture (furniturename );
In this way, the expected implementation is achieved through this. of course, this example is relatively simple, but it achieves code flexibility through the idea of the factory model. in application software system development, there are many places to consider using the factory model. for example, when writing data-Layer Code, taking into account the portability and scalability of the program, it is not an ideal implementation method to adopt the factory mode for different databases.