The fourth day of design model learning: 2.3 Factory method model and evolution

Source: Internet
Author: User

I. Factory Method mode
The FactoryMethod mode is the class creation mode. It defines a factory interface for creating product objects and delays the actual creation to the subclass.
The factory method mode is further abstract and promoted by the simple factory mode. Due to the use of polymorphism, the factory method pattern maintains the advantages of the simple factory pattern and overcomes its shortcomings.
In the factory method mode, the core factory class is no longer responsible for the creation of all products, but rather the specific creation work is handed over to the child class. This core class is only responsible for providing the interface that must be implemented by a specific factory, without touching the details of which product class is instantiated. This allows the Factory method mode to allow the system to introduce new products without modifying the factory role.
In the Factory Method mode, Factory classes and product classes usually have parallel hierarchical structures, which correspond one to one.


II. Factory Method role and structure:

Abstract factory role: it is the core of the factory method model and has nothing to do with applications. Any factory class of the object created in the mode must implement this interface.
Concrete Creator: this is a specific factory class that implements Abstract factory interfaces. It contains the logic closely related to applications and is called by applications to create product objects. There are two such roles: BulbCreator and TubeCreator.
Abstract Product role: The Super type of the object created in the factory method mode, that is, the common parent class of the Product object or the common interfaces. In, this role is Light.
Specific Product role: This role implements the interface defined by the abstract Product role. A specific product is created in a specific factory, which is usually one-to-one.

 

 

 

3. Program example:

 

 

Using System;

 

Namespace FactoryMethod

{

Public abstract class Light

    {

Public abstract void TurnOn ();

Public abstract void TurnOff ();

    }

 

Public class TubeLight: Light

    {

 

Public override void TurnOn ()

        {

Console. WriteLine ("TubeLight is TurnOn .");

        }

 

Public override void TurnOff ()

        {

Console. WriteLine ("TubeLight is TurnOff .");

        }

    }

 

Public class BulbLight: Light

    {

 

Public override void TurnOn ()

        {

Console. WriteLine ("BulbLight is TurnOn .");

        }

 

Public override void TurnOff ()

        {

Console. WriteLine ("BulbLight is TurnOff .");

        }

    }

 

Public abstract class Creator

    {

Public abstract Light Factory ();

    }

 

Public class TubeLightCreator: Creator

    {

Public override Light Factory ()

        {

Return new TubeLight ();

        }

    }

 

Public class BulbLightCreator: Creator

    {

Public override Light Factory ()

        {

Return new BulbLight ();

        }

    }

 

Public class Client

    {

Public static void Main (string [] args)

        {

Creator c1 = new TubeLightCreator ();

Creator c2 = new BulbLightCreator ();

 

Light l1 = c1.Factory ();

Light l2 = c2.Factory ();

 

L1.TurnOn ();

L1.TurnOff ();

 

Console. WriteLine ("------------------------------------------------------");

 

L2.TurnOn ();

L2.TurnOff ();

 

Console. ReadLine ();

        }

   }

}

 

Activity sequence diagram of factory methods

 

Activities include:
The client creates a BulbCreator object. The client holds this object type as Creator, while the actual type is BulbCreator. Then the client calls the factory method of BulbCreator, and then BulbCreator calls the BulbLight constructor to create the product BulbLight object.

IV. Factory method mode and simple factory mode
The difference between the factory method mode and the simple factory mode is not 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 mode is called the polymorphism factory mode because each factory class has a common interface or abstract parent class.
To add a new product object for system expansion, you only need to add a specific object and a specific Factory object. The original factory object does not need to be modified or the client needs to be modified, it is in line with the "open-closed" principle. The simple factory mode has to modify the Factory method after adding new product objects, and the scalability is poor.
After the factory method model degrades, it can be transformed into a simple factory model.

 

 

Factory Method mode evolution
Use an interface or abstract class
Abstract factory roles and abstract product roles can be implemented by interfaces or abstract classes.
Use multiple factory methods
Abstract factory roles can define more than one factory method so that specific factory roles can implement these different factory methods that provide different business logic, to meet the task of providing different product objects.
Product Recycling
The factory method always calls the constructor of the product class to create a new product instance, and then provides the instance to the client. In actual situations, the factory method can be quite complicated.
A common complex logic is to use product objects cyclically. The factory object registers the created products to a cluster and queries the cluster based on the product status requested by the customer. If a product object meets the requirements, the product is directly returned to the client. If such a product object does not exist in the aggregation, a new product object meeting the requirements is created, register the object to the cluster and return it to the client. "Flyweight Pattern" is such a Pattern.
  
Loss of polymorphism and degradation of patterns
The implementation of a factory method mode depends on the polymorphism of factory roles and product roles. In some cases, this mode may degrade.
The type returned by the factory method should be an abstract type, rather than a specific type. Clients that call factory methods should rely on abstract product programming, rather than specific products. If the factory only returns a specific product object, it violates the intention of the factory method and degrades, then it is no longer the factory model.
Hierarchical structure of the factory: The Factory object should have an abstract Super type. If there is only one specific factory class in the hierarchy, the abstract factory can be omitted, resulting in degradation.

Relationship between the Factory Method mode and other modes
Models related to the factory method model also include:
Template method mode, MVC mode, metadata mode, and memorandum mode
Another example:

Using System;

Using System. Collections;

 

Namespace FactoryMethod

{

// Product

Public abstract class Page

    {

    }

 

// ConcreteProduct

Public class SkillsPage: Page

    {

    }

 

// ConcreteProduct

Public class EducationPage: Page

    {

    }

 

// ConcreteProduct

Public class ExperiencePage: Page

    {

    }

 

// ConcreteProduct

Public class IntroductionPage: Page

    {

    }

 

// ConcreteProduct

Public class ResultsPage: Page

    {

    }

 

// ConcreteProduct

Public class ConclusionPage: Page

    {

    }

 

// ConcreteProduct

Public class SummaryPage: Page

    {

    }

 

// ConcreteProduct

Public class BibliographyPage: Page

    {

    }

 

// Creator

Public abstract class Document

    {

ArrayList pages = new ArrayList ();

 

Public ArrayList Pages

        {

Get {return pages ;}

        }

 

Public Document ()

        {

This. CreatePages ();

        }

 

Public abstract void CreatePages ();

    }

 

// ConcreteCreator

Public class Resume: Document

    {

Public override void CreatePages ()

        {

This. Pages. Add (new SkillsPage ());

This. Pages. Add (new EducationPage ());

This. Pages. Add (new ExperiencePage ());

        }

    }

 

// ConcreteCreator

Public class Report: Document

    {

Public override void CreatePages ()

        {

This. Pages. Add (new IntroductionPage ());

This. Pages. Add (new ConclusionPage ());

This. Pages. Add (new ResultsPage ());

This. Pages. Add (new SummaryPage ());

This. Pages. Add (new BibliographyPage ());

        }

    }

 

 

Public class 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 + "-------");

Foreach (Page page in document. Pages)

Console. WriteLine ("" + page );

            }

        }

    }

}

The fourth day of design model learning: 2.3 Factory method model and evolution

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.