Design mode C # description - factory method mode
Factory method mode is a class creation mode, called virtual construct sub-model or polymorphic factory model. Its intention is to define a factory interface that creates a product object, delays the actual creation work into the subclass.
Disadvantages of simple factory model:
Because the factory class has a logic of all products, if it is not possible to work, it will have a big impact on the system. If you add new products, you must modify the source code of the factory role.
The advantages of factory method model:
In the factory method mode, the core factory class is no longer responsible for all products creation, but will give the created work to the subclass. This core class is a role of an abstract factory, only responsible for giving interfaces that must be implemented by specific factory subclasses without contacting which product class instantiated details. This allows the factory method model to allow the system to introduce new products without modifying the specific plant role, making it superiority of simple factory models.
The specific implementation of this mode is discussed below:
Abstract Factory Role (CREATOR): Started with the core of factory method model, which provides an interface that creating an object's factory class.
ConcentecReetecreator: Responsible for the creation of specific product objects to implement the interface specified by Creator.
Abstract Product Role (Product): The super-type of the object to be created in the factory method mode, which specifies the interface that the product should have.
ConcreteProduct: Realize the interface specified by Product.
The sample code is as follows:
Creator:
Public Interface Creator
{
Product factory (); // factory method
}
Concretecreator1:
Class Concretecreator1: Creator
{
Public product factory () // factory method
{
Return New ConcreteProduct1 ();
}
}
Concretecreator2:
Class Concretecreator2: Creator
{
Public product factory () // factory method
{
Return New ConcreteProduct2 ();
}
}
Product:
Public Interface Product
{
}
ConcreteProduct1:
Class ConcreteProduct1: Product
{
Public contRoduct1 ()
{
Console.WriteLine ("Creat ConcreteProduct1);
}
}
ConcreteProduct2:
Class ConcreteProduct2: Product
{
Public contRoduct2 ()
{
Console.writeline ("Creat ConcreteProduct2);
}
}
Client:
Class Client
{
Private static creator1, creator2;
Private statino
[Stathread]
Static void
Main
(String [] ARGS)
{
Creator1 = new concretecreator1 ();
PRODUCT1 = CREATOR1.FACTORY ();
Creator2 = new concretecreator2 ();
Product2 = creator2.factory ();
}
}