C # Design Patterns-factory methods

Source: Internet
Author: User

First, the factory method (Factory) mode

The Factory method (FactoryMethod) mode is the creation mode of a class, which is intended to define a factory interface that creates a product object, deferring the actual creation to subclasses.

The factory method model is a further abstraction and generalization of the simple factory model. Due to the polymorphism, the factory method pattern maintains the advantages of a simple factory model and overcomes its drawbacks.

In the factory method model, the core factory class is no longer responsible for the creation of all the products, but rather the specific creation work to the subclass to do. This core class is only responsible for giving the interface that a specific factory must implement, without touching on which product class is instantiated in this detail. This allows the factory method mode to allow the system to introduce new products without modifying the factory role.

In factory method mode, factory classes and product classes tend to have parallel hierarchical structures that correspond to one by one of them.

Second, Factory method mode role and structure:

Abstract Factory (Creator) Role: is the core of the factory method pattern, regardless of the application. Any factory class of objects created in the schema must implement this interface.

Specific Factory (concrete Creator) Role: This is the specific factory class that implements the abstract factory interface, contains the logic that is closely related to the application, and is called by the application to create the Product object. There are two such roles in: Bulbcreator and Tubecreator.

Abstract Product Role: The Super-type of the object created by the factory method pattern, which is the common parent or co-owned interface of the product object. In, this role is light.

Specific Products (concrete product) Role: This role implements the interface defined by the abstract product role. A specific product has a specific factory-created, often one by one correspondence between them.

Iii. Examples of procedures:

usingSystem; Public Abstract classlight{ Public Abstract voidTurnOn ();  Public Abstract voidturnoff ();} Public classbulblight:light{ Public Override voidTurnOn () {Console.WriteLine ("Bulb Light are turned on"); }     Public Override voidturnoff () {Console.WriteLine ("Bulb Light is turned off"); }} Public classtubelight:light{ Public Override voidTurnOn () {Console.WriteLine ("Tube Light are turned on"); }     Public Override voidturnoff () {Console.WriteLine ("Tube Light is turned off"); }} Public Abstract classcreator{ Public AbstractLight Factory ();} Public classbulbcreator:creator{ Public OverrideLight Factory () {return Newbulblight (); }} Public classtubecreator:creator{ Public OverrideLight Factory () {return Newtubelight (); }} Public classclient{ Public Static voidMain () {Creator C1=NewBulbcreator (); Creator C2=NewTubecreator (); Light L1=C1.        Factory (); Light L2=C2.        Factory (); L1.        TurnOn (); L1.        Turnoff (); Console.WriteLine ("-----------------"); L2.        TurnOn (); L2.    Turnoff (); }}

Activity sequence diagram for factory methods

The activity process includes:

The client creates the Bulbcreator object, and the client holds the type of this object is creator, and the actual type is bulbcreator. The client then calls Bulbcreator's Factory method, and then Bulbcreator calls the Bulblight constructor to create the product Bulblight object.

Iv. Factory method model and simple factory model

The difference between the factory method pattern and the simple factory model is not very obvious. The core of the Factory method class is an abstract factory class, while the simple factory model places the core on a specific class.

The factory method pattern has an alias called the Polymorphism factory pattern 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 need to add a specific object and a specific factory object, the original factory objects do not need to make any changes, and do not need to modify the client, well in line with the "open-closed" principle. The simple factory model has to modify the factory method after adding the new Product object, the extensibility is not good.

The factory method model can evolve into a simple Factory mode after degradation.

Model Evolution of Factory method

Using interfaces or abstract classes
Both abstract factory roles and abstract field-frequency roles can be selected for implementation by interfaces or abstract classes.

Using Multiple factory methods
Abstract factory roles can specify more than one factory method, which enables specific factory roles to implement these different factory methods, which can provide different business logic to meet the task of providing different product objects.

Recycling of products
The factory method always invokes the constructor of the product class to create a new product instance and then provides the instance to the client. And in the real world, what the factory method does can be quite complicated.

A common complex logic is to recycle product objects. The factory object registers the product that has already been created into a cluster, and then queries the aggregation based on the product status requested by the customer. If there is a product object that satisfies the requirement, the product is returned directly to the client; if there is no such product object in the aggregation, a new product object is created that satisfies the requirement, then the object is enlisted in the aggregation and returned to the client. The "Flyweight pattern" is one such pattern.

Loss of polymorphism and degeneration of patterns
The implementation of a factory method pattern relies on the polymorphism of factory roles and product roles. In some cases, this pattern can degenerate.

The type that the factory method returns should be an abstract type, not a specific type. Clients calling the factory method should rely on abstract product programming, rather than specific products. If the factory only returns a specific product object, it violates the intent of the factory method, degradation, then is no longer a factory mode.

Factory Hierarchy: Factory objects should have an abstract super type. If there is only one specific factory class in the hierarchy, the abstract factory can be omitted and degraded.

Vi. the relationship between Factory method model and other modes

Patterns related to the factory method model also include:
Template method mode, MVC mode, enjoy meta mode, Memo mode

Seven, another example

//Factory Method Pattern-Real World ExampleusingSystem;usingSystem.Collections;//"Product"Abstract classpage{}//"Concreteproduct"classskillspage:page{}//"Concreteproduct"classeducationpage:page{}//"Concreteproduct"classexperiencepage:page{}//"Concreteproduct"classintroductionpage:page{}//"Concreteproduct"classresultspage:page{}//"Concreteproduct"classconclusionpage:page{}//"Concreteproduct"classsummarypage:page{}//"Concreteproduct"classbibliographypage:page{}//"Creator"Abstract classdocument{// Fields    protectedArrayList pages =NewArrayList (); //Factory Method     Public Abstract voidcreatepages (); //Constructor    protectedDocument () {createpages (); }    //Properties     PublicArrayList Pages {Get{returnpages;} }}//"Concretecreator"classresume:document{//Factory Method Implementation     Public Override voidcreatepages () {pages. ADD (Newskillspage ()); Pages. ADD (Neweducationpage ()); Pages. ADD (Newexperiencepage ()); }}//"Concretecreator"classreport:document{//Factory Method Implementation     Public Override voidcreatepages () {pages. ADD (Newintroductionpage ()); Pages. ADD (Newresultspage ()); Pages. ADD (Newconclusionpage ()); Pages. ADD (Newsummarypage ()); Pages. ADD (Newbibliographypage ()); }}/// <summary>///Factorymethodapp Test/// </summary>classfactorymethodapp{ Public Static voidMain (string[] args) {        varDocs =Newdocument[2]; //note:constructors call Factory Methoddocs[0] =NewResume (); docs[1] =NewReport (); //Display Document pages        foreach(Document documentinchdocs) {Console.WriteLine (""+ Document +" ------- "); foreach(Page pageinchdocument. Pages) Console.WriteLine (" "+page); }    }}

C # Design Patterns-factory methods

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.