See the introductory article of the nice design pattern, attached to this:
Original posted link:
http://www.cnblogs.com/zhenyulu
I. Factory Method mode
FactoryMethod mode is the creation mode of the class, which is intended to define a factory interface that creates a product object and delays the actual creation work into the subclass.
The factory method model is a further abstract and promotion of simple factory models. Due to the use of polymorphism, the factory method model maintains the advantages of simple factory models, and overcomes its shortcomings.
In the factory method mode, the core factory class is no longer responsible for the creation of all products, but to give the specific creation work to the subclass. This core class is only responsible for giving the interface that the specific factory must implement, without contacting which product class is instantiated. This allows factory method patterns to allow the system to introduce new products without modifying plant roles.
In Factory Method mode, factory class and product classes often have parallel level structures, and they correspond to one by one.
Second, Factory Method mode role and structure:
Abstract Factory Role: It is the core of the factory method model and is not related to the application. Any factory class for objects created in the mode must implement this interface.
Concrete Creator Role: This is a specific factory class that implements abstract factory interfaces, which contains closely related to applications, and is subject to application calls to create product objects. There are two such roles in the above figure: Bulbcreator and Tubecreator.
Abstract Product Role: The super-type of the object created by the factory method mode, that is, the common parent class of the product object or the joint owned interface. In the above figure, this role is Light.
Concrete Product Role: This role implements an interface defined by an abstract product role. A specific product has a special specific factory creation, and between them often correspond to one.
Third, the program example:
Using
System;
public
Abstract
Class
Light
{Public abstract void turnon (); public abstract void turnoff ();
public
Class
Bulblight: Light
{Public override void () {Console.WriteLine ("bulb light is turned on");} public override void turnoff () {console.writeline ("bulb light is turned off";}}
public
Class
Tubelight: Light
{Public override void turnon () {Console.WriteLine ("Tube Light IS Turned ON");} PUBLIC OVERRIDE VOID Turnoff () {Console.WriteLine ("Tube Light IS Turned Off";}}
public
Abstract
Class
Creator
{Public abstract light fact factory ();
public
Class
Bulbcreator: Creator: CREATOR
{Public override light factory () {return new bulblight ();}}
Publicclass
Tubecreator: CREATOR
{Public override light factory () {return new tubelight ();}}
public
Class
Client
{CREATOR C1 = New Bulbcreator (); Creator C2 = New Tubecreator (); Light L1 = C1.FACTORY (); Light L2 = C2.Factory (); l1.turnon (); l1. "---------------"); l2.turnon (); l2.turnoff ();}}
Factory method activity sequence diagram
The activity process includes:
The client creates a BulbCreator object, and the client holds this object is Creator, and the actual type is Bulbcreator. The client then calls the Bulbcreator's Factory method, and then Bulbcreator calls Bulblight's constructor creates a product Bulblight object.
Fourth, factory method mode and simple factory model
Factory method model is not very obvious with simple factory model re-structure. The core of the factory method is an abstract factory class, while simple factory model puts the core in a specific class.
Factory method model has an aliasing polymorphic factory model because the specific factory class has a common interface, or a common abstract parent class.
When the system extension needs to add a new product object, just add a specific object and a specific factory object, the original factory object does not need to make any modifications, nor does it need to modify the client, which is very good to meet "Open-Closed" in principle. Simple factory model has to modify the factory method after adding new product objects, and the extensibility is not good.
After the plant method mode is degraded, it can evolve into a simple factory model.
Five, Factory Method mode evolution
Using an interface or abstract class abstract factory role and abstract field frequency role can be implemented by an interface or abstract class.
The use of multiple factory methods Abstract factory roles can specify more than one factory approach to enable specific factory roles to provide different factory methods, which can provide different business logic to meet the tasks of providing different product objects.
The cycle of the product uses factory methods to always call the product class constructor to create a new product instance and then provide this instance to the client. In the actual situation, the fact that the factory method does can be quite complicated.
A common complex logic is cycling using product objects. Factory objects will register the products that have been created into a gather, and then query the aggregated query according to the product status requested by the customer. If there is a product object that meets the requirements, return the product directly; if you don't have such a product object, create a new product object, then register this object into the gathering, then return to the customer end. "Flyweight Pattern" is like this.
The loss of polymorphism and the degenerate degradation of a factory method model depends on the polymorphism of factory role and product role. In some cases, this mode can be degraded.
The type returned by the factory method should be an abstract type, not a specific type. Clients calling factory methods should rely on abstract product programming, not specific products. If the factory only returns a specific product object, it violates the intention of the factory method, degrading, and it is no longer the factory model.
Factory level structure: factory objects should have an abstract super-type. If there is only one specific factory class in the level structure, the abstract factory can omit and degrade. 6. Relationship between Factory Method mode and other modes
The model related to the factory method mode also includes: template mode, MVC mode, enjoys, memo mode
Seven, another example
//
Factory Method Pattern - Real World EXAMPLE
Using
System;
Using
System.collections;
//
Product "
Abstract
Class
Page
{}
//
"Concreteproduct"
Class
Skillspage: Page
{}
//
"Concreteproduct"
Class
EducationPage: Page
{}
//
"Concreteproduct"
Class
ExperiencePage: Page
{}
//
"Concreteproduct"
Class
IntroductionPage: Page
{}
//
"Concreteproduct"
Class
Resultspage: Page: Page
{}
//
"Concreteproduct"
Class
ConclusionPage: Page: Page
{}
//
"Concreteproduct"
Class
Summarypage: Page
{}
//
"Concreteproduct"
Class
Bibliography: Page
{}
//
"Creator"
Abstract
Class
Document
{// Fields protected ArrayList pages = new ArrayList (); // Constructor public Document () {this.CreatePages ();} // Properties public ArrayList Pages {get {return pages;}} // Factory Method abstract public void CreatePages ();
//
Concretecreator
Class
Resume: Document
{/ Factory Method Implementation Override Public Void CreatePages () {pages.add (new skillspage ()); pages.add ());}}
//
Concretecreator
Class
Report: Document
{// Factory Method implementation override public void CreatePages () {pages.Add (new IntroductionPage ()); pages.Add (new ResultsPage ()); pages.Add (new ConclusionPage ()); pages.Add (new SummaryPage ( )));
/ ** /
///
FactoryMethodApp
{Public static void main (string [] args) {document [] DOCS = new document [2]; // Note: Constructors call factory method DOCS [0] = new resume (); DOCS [1] = new report () ; // display document pages foreach (document document in docs) {console.writeline (" Document " ------- ") Console.Writeline (" Page);}}}
See the introductory article of the nice design pattern, attached to this:
Original posted link:
http://www.cnblogs.com/zhenyulu
First, abstract factory (Abstract Factory) mode
Abstract factory model is the most abstract and most general form of all forms of factory models.
In order to facilitate the introduction of abstract factory models, introduce a new concept: Product Family. The so-called product family refers to a family that is located in different product level structures and functions. Figure:
There are four products in the figure, which are distributed in three different product level structures. Just indicate that the product family in a product and its level structure are to be specified, this product can be unique.
Introducing abstract factory model
The so-called abstract factory refers to all objects of a plant level structure that can create a product family that belongs to different product levels. If you are described by the figure, as shown below:
Second, the structure of the Abstract Factory mode:
The things described in the figure are described below:
Abstract Factory Role: The role is the core of the factory method model, which is unrelated to the business logic of the application system.
Concent Factory Role: This role creates an instance of a product directly under the call. This role contains the logic of the appropriate product object, and this logic is closely related to the commercial logic of the application system.
Abstract Product (ABSTRACT Product) Role: The class of this role is the parent class of the object created by the factory method mode, or the interface they share.
Concrete Product Role: Any product object created by abstract factory modes is an example of a specific product class. This is something that the client is ultimately needed, and it must be full of commercial logic of the application system.
Third, the program example:
The program demonstrates the structure of an abstract factory that does not have any actual value.
//
Abstract Factory Pattern - Structural Example
Using
System;
//
"AbstractFactory"
Abstract
Class
AbstractFactory
{// Methods Abstract Public AbstractProducta CreateProducta (); Abstract Public AbstractProductB CreateProductB ();} //
"ConcreteFactory1"
Class
Concretefactory1: AbstractFactory
{// Methods Override Public AbstractProducta CreateProducta () {Return New ProductB () Override Public AbstractProductB CreateProductB () {Return New ProductB1 ();}}
//
"ConcreteFactory2"
Class
Concretefactory2: AbstractFactory
{// Methods Override Public AbstractProducta CreateProducta () {Return New ProductB () Override Public AbstractProductB CreateProductB () {Return New ProductB2 ();}}
//
"AbstractProducta"
Abstract
Class
AbstractProducta
{}
//
"AbstractProductB"
Abstract
Class
AbstractProductB
{// Methods Abstract Public Void Interact (AbstractProducta A);}
//
ProductA1 "
Class
ProductA1: AbstractProducta
{}
//
ProductB1
Class
ProductB1: AbstractProductB
{// Methods Override public void interact (AbstractProducta a) {console.writeline (this "interacts with" a);}}
//
ProductA2
Class
Producta2: AbstractProducta
{}
//
ProductB2
Class
ProductB2: AbstractProductB
{// Methods Override public void interact (AbstractProducta a) {console.writeline (this "interacts with" a);}}
//
"Client" - The Intertion Environment of the Products
Class
ENVIRONMENT
{// Fields private AbstractProductA AbstractProductA; private AbstractProductB AbstractProductB; // Constructors public Environment (AbstractFactory factory) {AbstractProductB = factory.CreateProductB (); AbstractProductA = factory.CreateProductA ();} // Methods public void Run () {AbstractProductB. Interact (AbstractProducta);}} / ** /
///
Class
ClientApp
{Public static void Main (string [] args) {AbstractFactory factory1 = new ConcreteFactory1 (); Environment e1 = new Environment (factory1); e1.Run (); AbstractFactory factory2 = new ConcreteFactory2 (); Environment e2 = new Environment (factory2 ); E2.Run ();}}
Fourth, use abstract factory model in what case:
In the following cases, you should consider using abstract factory modes:
A system should not depend on how the product instance is created, combined, and expressed, which is important for factory models of all forms. This system has more than one product family, and the system only consumes one of the product. It is used with products that belong to the same product family, which must be reflected in the design of the system. The system provides a library of a product class, all products appear in the same interface, so that the client does not rely on implementation.
Five, the origin of the abstract factory
It is said that the earliest application is used to create systems that can be operated in a window environment of different operating systems. For example, in Windows and UNIX systems have a window environment, in each operating system, there is a component family consisting of window components. We can give a functional description by an abstract role, and the specific subclass gives specific implementations under different operating systems, as shown:
It can be found that there are two product grade structures in the product classes, which are Button and Text; at the same time, there are two product families: UNIX product family and Windows product family.
The system's creation requirements for product objects are satisfied by a plant level structure. There are two specific factory characters, namely UnixFactory and WinFactory. The UnixFactory object is responsible for creating products in the UNIX product family, while WinFactory is responsible for creating products in a Windows product family.
It is apparent that a system can only run in a window environment of an operating system without running on different operating systems. Therefore, the system can actually consume products that belong to the same product family.
In modern applications, the scope of use of abstract factory model has been greatly expanded, no longer asking the system to consume one product family.
6. Implementation in the ABSTRACT FACTORY mode in the actual system
Herbivore: Herbal animal Carnivore: Carnivore Bison: ['Baisn], American or European Bison
The actual code demonstrates an abstract factory that creates different animals in a computer game. Although animal species under different mainland are different, the relationship between the animals remains.
//
Abstract Factory Pattern - Real World Exampleusing
System;
//
"AbstractFactory"
Abstract
Class
ContinentFactory
{// Methods Abstract Public Herbivore CreateHerbivore (); Abstract Public Carnivore CreateCarnivore ();
//
"ConcreteFactory1"
Class
AfricaFactory: ContinentFactory
{// Methods Override public herbivore createherbivore () {Return New WildeBeest ();} {return new lion ();}}
//
"ConcreteFactory2"
Class
Americafactory: ContinentFactory
{//Methods override public herbivore creteherbivore () {return new bison ();} Override public carnivore createcarnivore () {return new wolf ();}}
//
"AbstractProducta"
Abstract
Class
Herbivore
{}
//
"AbstractProductB"
Abstract
Class
Carnivore
{// Methods Abstract Public Void Eat (Herbivore H);
//
ProductA1 "
Class
Wildebeest: Herbivore
{}
//
ProductB1
Class
Lion: Carnivore
{// Methods Override Public Void Eat (Herbivore H) {// Eat Wildebeest Console.writeline (this "EATS" H);}}
//
ProductA2
Class
Bison: Herbivore
{}
//
ProductB2
Class
Wolf: carnivore
{// Methods Override Public Void Eat (Herbivore H) {// Eat Bison Console.WriteLine (this "EATS" H);}}
//
"Client"
Class
Animalworld
{// Fields private Herbivore herbivore; private Carnivore carnivore; // Constructors public AnimalWorld (ContinentFactory factory) {carnivore = factory.CreateCarnivore (); herbivore = factory.CreateHerbivore ();} // Methods public void RunFoodChain () {carnivore. Eat (Herbivore);}}
/ ** /
///
GameApp
{Public static void Main (string [] args) {// Create and run the Africa animal world ContinentFactory africa = new AfricaFactory (); AnimalWorld world = new AnimalWorld (africa); world.RunFoodChain (); // Create and run the America Animal World ContinentFactory America = new AmericafaFactory (); World = New Animalworld (America); World.Runfoodchain ();}}
Another example of an abstract factory:
How to design abstract factory for staying.
Seven, "Open-Closed" principle
"Open-Closed" principle requires the system to open open and enclose the modification. The purpose of enhancing its function is achieved by expanding. For systems involving multiple product families and multiple product levels, their functional enhancements include two aspects:
Increase product: Abstract Factory is very good to support the "open-closed" principle.
Add a level structure of new products: You need to modify all factory characters, not well supporting "Open-Closed" principles.
Combining, abstract factory model supports increasing new products in a slope manner, which is convenient for the increase in the new product family, and does not provide this convenience for the increase in new product rating.