Misunderstanding of Factory Method mode: Is Factory Method a simplified Abstract Factory?

Source: Internet
Author: User

FactoryMethod is a relatively simple creation mode, but it is rare to understand or use it correctly. Many examples do not reflect the core idea of Factory Method, only a simplified Abstract Factory is implemented, and the explanation given is that the Factory Method mode solves the requirement change of "single object", and the Abstract Factory mode solves the requirement change of "series object.

Imagine if we regard 1 as a special case of N, then a product series may contain only one object. Can we consider Factory Method as a simplified Abstract Factory? In fact, the Factory Method mode and Abstract Factory mode belong to the object creation mode, and AbstractFactoryClassGenerallyFactory Method modeImplementation, and the effect can be used to connect parallel class layers, but these two models have essential differences in ideology. Text on the internet is copied and incorrect results are also transmitted everywhere. The previous article introduced the Builder mode that is widely misused. This article continues to be named as Factory Method.

 

1. Factory Method (Form Design Patterns GOF) 1.1 intent

Defines an interface for creating objects,Let the subclass decide which class to instantiate. Factory Method to instantiate a classDelay to its subclass.

1.2 alias

Virtual Constructor (Virtual Constructor)

1.3 Practicality

InMeetingThe Factory Method mode can be used in the following cases:

  1. When a classDon't knowWhen it is necessary to create a class object;
  2. When a class is expectedIts subclass specifies the object it creates.Time;
  3. When the class changesThe role of creating an object is delegated to one of multiple help sub-classesAnd when you want to localize the Helper subclass information of the proxy. (This translation is very sweaty. the original English text is: classes delegate responsibility to one of several helper subclasses, and you wantLocalizeThe knowledgeWhich helper subclass is the delegate.)
1.4 Structure:(Screenshot taken directly from the book)

 

1.5 Additional instructions
  1. The above is the GOF's explanation of FactoryMethod.InheritanceIdea: Creator)Don't knowThe object (Product) of the class that must be created, so an interface is left and delegated to the subclass (ConcreteCreator) for implementation (rewriting ).
  2. There is alsoAnOperation Method, GOF also made a special comment for this Method, which is a Template Method (Template Method ),It calls FactoryMethod (). In the related mode, GOF also repeatedly mentions:"The factory Method is usually called in the Template Method.", Many examples of Factory Method are directly ignoring this Method and annotation, resulting in misuse of the Factory Method mode.
  3. ThisNo "Client" class is shown in the class diagram.Abstract Factory has a Client class. It should not be a painting when you are happy. If you are unhappy, you will not draw it.

Continue with the previous article, starting with several distorted examples.

 

2. Two simplified versions of the Abstract Factory mode 2.1 Abstract Factory mode structure

(Screenshot taken directly from the book)

2.2 When the product series only contains one object

Abstract Factory is used to create a product series. A product series may contain multiple (N, N> = 1) objects.Consider 1 as a special case of N., A product series may contain only one object, and the structure is as follows:

1. Example of Factory Method in "big talk Design Pattern": (screenshot from the book)

2. <. Net design mode (5): Factory Method>

Http://www.cnblogs.com/Terrylee/archive/2006/01/04/310716.html, directly referencing two pictures in the original article:

Because there are two graphs, I have not done any processing, and I moved them directly. If I draw an aggregation line, it is similar to the previous example.

2.3 descriptions of the two examples

When introducing the Abstract Factory mode, GOF mentioned "AbstractFactoryClassGenerallyFactory Method modeBut they can also be implemented using Prototype ". Although the Factory Method mode is used in the above two examples to see only some of the parts, but in combination with the original author's elaboration and extension points,Globally, it does not reflect the idea of Factory Method..

 

3. Difference between Factory Method and Abstract Factory

Although the Factory Method mode and Abstract Factory mode belong to the same object creation mode, and the AbstractFactory class is usually implemented in the Factory Method mode, and the results are both effective.Can be used to connect parallel class Layers(Factory Method is not limited to this), but these two models have essential differences in ideology. The Factory Method and Abstract Factory that I understand have the following differences:

3.1 Object Responsibility: Factory in Abstract Factory has only the unique responsibility of creating an object (a product series). Creator in Factory Method often has actual logic and meaning.

Looking back at the structure of the Factory Method, we can see that there isAnOperation Method, GOF also made a special comment for this Method, which is a Template Method (Template Method ),It calls FactoryMethod (). In the related mode, GOF also repeatedly mentions:"The factory Method is usually called in the Template Method.". That is, the Factory Method is usually called in other methods of the Creator class. Why?

GOF uses the following example to introduce the Factory Method mode:

In this example, the Application assumes the Creator role, and the MyApplication assumes the ConcreteCreator role.Application is a fresh class that abstracts specific things (applications) and has its own responsibilities, not just a new Document object;Its NewDocument Method (Template Method) calls CreateDocument,The Application object is actually the user (Client) of the Document object)Factory Method highlights the creation of Procuct (Document in this example), so there is no additional Client class in the structure diagram, and it does not need to appear.

(Add [Special thanks to soudog on the first floor] :) the creator of the Factory Method also contains the unchanged code logic and change section, butThe variation part can be rewritten by a subclass (override)Abstract facotryThe changes are extracted to the factory class., Separates the unchanged code logic (Client) from the change part more thoroughly, and then connects the Client and factory through aggregation.

3.2 Scaling: Abstract Factory focuses on horizontal scaling, while Factory Method focuses on Vertical Scaling

The concepts of "horizontal scaling" and "Vertical Scaling" are just a bit of a joke. The following two figures can be used to describe:

First look at Abstact Factory (the Red Arrow and direction in the intent ):

Abstract Factory:Different ConcreteFactory, create different product series, Factory can replace with each other, thus replacing the product series. Client-oriented interface (AbstractFactory and AbstractProductA) programming, the Factory class encapsulates the creation of the object series, the specific products are also separated from the Client, so that weEasy to switch product series. As shown in the figure, the newly added ProductA3/B3 and ConcreteFactory3 are inParallel class hierarchy. This is what I call "horizontal scaling "-_-

Supplement: although other ConcreteFactory such as ConcreteFactory4 can be added to inherit the existing ConcreteFactory, it seems that ConcreteFactory4 and other ConcreteFacotry do not belong to the same class level and do not look "horizontal. However, from the Client perspective, ConcreteFactory4 and ConcreteFactory1 ~ 3. In a sense, it is equivalent to creating a series of products, and they can be replaced with each other to replace the product series. That is, in the logic sense, it can still be regarded as "horizontal scaling ".

Let's look at the Factory Method (dark green arrow and direction in the intent )::

Factory Method: subclass (ConcreteCreator)RewriteThe create product interface (FactoryMethod () of the parent class (Creator ()). Combined with the practicality of the Factory Method and the example of Application/Document, the ConcreteCreator determines the type of Product to be created based on the logic encapsulated by ConcreteCreator itself (as described in the previous section, creator/ConcreteCreator is a practical class.Inheritance relationship between ConcreteCreator and CreatorThey are at different class levels. This is what I call vertical scaling ".

Supplement: although you can add ConcreteCreator3/ConcreteProduct3, as shown in, so that the ConcreteCreator does not look vertical. However, here we emphasize the relationship between Creator and ConcreteCeator, and between Product and ConcreteProduct. From the Client (not shown in the figure) of the Creator, different concretecreators cannot be replaced. For example, in the Application/Document example, when the Client operates a drawing Application, it must use DrawingApplication and DrawingDocument, rather than TextApplication and TextDocument. Although in the "effect" section, GOF explains that the Factory Method can connect parallel class layers and take Figure and Manipulator as examples, as shown in:

In terms of graphical structure, Creator (LineFigure and TextFigure) is in a parallel class level with Product (LineManipulator and TextManipulator. However, it is worth noting that between products and between TextManipulator cannot be replaced. Client-oriented interface (Figure and Manipulator) programming. When the Client operates a Line segment, it must use LineFigure and LineManipulator. When the Client operates a Text segment, textFigure and TextManipulator must also be used;ConcreteDocument depends on the context of the Client. ConcreteFigure cannot be replaced with each other.. The abstract Creator interface does not know the context of the Client or the Product to be created. Therefore, it is delegated to the subclass for rewriting. Factory Method emphasizes the inheritance relationship between Procuct and ConcreteProduct, Creator and ConcreteCreator, and sub-class ConcreteCreator)RewriteThe create product interface (FactoryMethod () of the parent class (Creator) can be viewed as "vertical extension" logically ".

In the implementation section, the example of MazeGame provided by GOF is as follows:

The created product is omitted in the figure. Although EnchantedMazeGame and BomedMazeGame can be exchanged here, pay attention to the role of MazeGame (It is an abstraction of a specific thing [maze game], not just an interface for creating various products), And his CreateMaze method (this method is a template method ). It is repeatedly emphasized that the interface for inheriting the parent class and rewriting the Product creation is used.

3.3 usage: Abstract Factory's idea is to aggregate (Composition), while the idea of Factory Method is to inherit (Inheritance)

After introducing the five creation modes, GOF has a discussion summary: "There are two common methods to parameterize the system using the classes of the objects created by a system: one is to generate a subclass of the class for creating the object, which corresponds to the Factory Method mode "; the other Method for parameterization of the system is more dependent on Object composition: defining an object defines the class of the product object and uses it as the parameter of the system. This is the key feature of the Abstract Factory, Builder, and Prototype modes."

For Factory Method, taking Application/Document as an example, Application (Creator) must use Document (Product) and regard Document as a "parameter" of the Application Operation, then the specific Document (ConcreteProduct) is created by the Application of a specific Application (subclass of ConcreteCreator.

For Abstract Factory, let's take a look at the implementation of GOF:

The painting is messy. The focus is on the red comments in the upper-left corner, which is interpreted as the Composition idea of Abstract Factory: MazeGame aggregates a MazeFactory.

The other two points should be noted: (1). Pay attention to the role of MazeFactory: only a group of interfaces for creating objects; (2). MazeFactory contains a group of Factory methods.

 

4. Summary

The Factory Method mode is not a simplified Abstract Factory; on the contrary, the Factory class in the Abstract Factory mode can be regarded as a simplified Factory Method mode (for example, two examples at the beginning of this article ), it unifies Creator's responsibilities, so that it has only the responsibility of creating objects.

Factory Method and Abstract Factory can be used to connect parallel class layers in terms of effects (Factory Method is not limited to this), but these two modes have essential differences in ideology:

  1. Objects: Factory in Abstract Factory has only the unique responsibility of creating objects (a product series), while Creator in Factory Method has actual logic and meaning.
  2. Extension: Abstract Factory focuses on horizontal expansion, while Factory Method focuses on vertical expansion.
  3. Abstract Factory thought is aggregation, while Factory Method thought is inheritance.

Related mode:Abstract Factory is often implemented using the Factory method. The factory Method is usually called in the Template Method..

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.