JavaScript design pattern Theory and Combat: Factory method mode

Source: Internet
Author: User
Tags closure

Starting from the shortcomings of the simple factory model, this paper introduces the factory method model, introduces the basic knowledge of the factory method pattern, realizes the main points and the application scenario, and finally illustrates the application of the factory method pattern.
In the previous "JavaScript Design model Theory and Practice: Simple Factory Model", we introduced the knowledge of simple factories and some applications. The simple factory model has a unique factory class, which has the advantage that the instantiation of all product classes is centrally managed and easy to understand, but this is both an advantage and a disadvantage. If
The number of product classes is small and does not change very often, we can directly take advantage of the simple factory model, but sometimes, the demand is always changing, the product class is also likely to increase at any time, if the use of simple Factory mode, it is inevitable to modify the factory class code. To solve this problem, we need to mention the factory method model that we are going to talk about today.

Basic concepts

Factory method Mode: No longer have a unique factory class to create a product, but instead to give different products to the corresponding factory subclass to achieve. Each product is created by a sub-factory responsible for production. If you add a new product, you need to add new sub-factories and products without needing to modify the other factory code.

There are three main types of factory method models:
1. Abstract Factory class: Responsible for defining the public interface that creates the product.
2. Product sub-factory: Inherit abstract factory class, implement the interface provided by abstract factory class
3. Each product's respective product class

Implementation of factory method pattern

First, we transform the code of the Simple factory model in the article "JavaScript Design pattern Theory and combat: Simple Factory mode". Here is the code for the Simple factory formula:

1 varProductenums = {2Flight: "Flight",3Hotel: "Hotel"4 };5 functionFlight () {6Console.log ("This is Flight");7 }8 functionHotel () {9Console.log ("This is Hotel");Ten } One varProductfactory = (function () { A     varProductfactories = { -"Flight":function () { -             return NewFlight (); the         }, -"Hotel":function () { -             return NewHotel (); -         } +     }; -  +     return { ACreateproduct:function(producttype) { at             returnProductfactories[producttype] (); -         } -     } - })(); - functionUser () { -      This. Shopcart = []; in } -User.prototype = { to Constructor:user, +Orderfunction(producttype) { -          This. Shopcart.push (Productfactory.createproduct (ProductType)); the     } *}

To modify the above code into a factory method pattern, first construct an abstract factory class. In JS, due to the concept of our abstract class, we can't do the abstract factory class like java,c#, but we can simulate it. The code is as follows

1 function abstractfactory () {2} 3 function () {4     Throw "No implementation of this method"; 5 }

In this code, define a factory class, and then define its method Createproduct, this method simulates the abstract method, does not provide the concrete implementation, but throws the error, the inheriting factory class is going to implement the concrete method, otherwise will throw the wrong, this simulates an abstract factory class.
After defining the abstract factory class, now all we have to do is define a sub-factory to implement it, and we define two sub-factories flightfactory and Hotelfactory respectively.

1 functionflightfactory () {2Abstractfactory.call ( This);3 }4Flightfactory.prototype =Newabstractfactory ();5FlightFactory.prototype.createProduct =function () {6     return NewFlight ();7 }8 functionhotelfactory () {9Abstractfactory.call ( This);Ten } OneHotelfactory.prototype =Newabstractfactory (); AHotelFactory.prototype.createProduct =function () { -     return NewHotel (); -}

The code above defines two sub-factory classes, each inheriting the abstract factory class, and then implementing the Createproduct method, each of which is created in its own factory class.
How does the client invoke it?

1 var New flightfactory (); 2 factory.createproduct (); 3 New hotelfactory (); 4 factory.createproduct ();

Doubtful answers

First we need to understand a concept: the Open closure principle.
Software entities should be extensible but not modifiable, which is open to extensions but closed to modifications. Embodied in two areas:
(1) Open to expansion, the product has new requirements or changes, you can extend the existing code to adapt to the new changes
(2) To modify the closed, the class once the design is completed, it should not be modified.

Here's a few questions.
1, compared to the simple factory model, the factory method model has increased an abstract factory class and a number of sub-factory classes, so that the code is not more complex?
Indeed, the code is more complex than the simple factory model, introducing an abstraction layer, and a sub-factory, which increases the complexity and difficulty of understanding the code. However, compared to the simple factory model, the maintainability and extensibility of the code are improved, and when new products are added, only the corresponding product classes and product factory classes need to be added, without modification to the abstract factory class and other sub-factories. More in line with the object-oriented open closure principle.
Of course, specific scenarios specific analysis, complexity and extensibility compared to how to shed, in the use of the actual scene to analyze.
2, when the client calls, each product still need to know the specific factory class to invoke, as if the difference is not big?
And the simple factory model is the difference between: we will determine which product class to use the code from the factory class transferred to the calling client here, if there are new features to add, we have to modify the client code instead of the factory class code, so as to comply with the open closure principle.

Summarize the key points of implementation

In JS, we implement the factory method model mainly consists of 3 roles:
1. Abstract Factory class: A statement providing a factory method
2. Sub-factory class: Factory method to implement abstract factory class
3. Product Categories: Specific product Categories

Advantages and Disadvantages

Pros: Overcomes the drawbacks of the simple factory model. If you need to add new product classes without modifying existing systems, you only need to add new plant classes and product classes, each factory class encapsulates the creation details of the product objects, and the system has good flexibility and scalability.
Disadvantage: the addition of new products and the need to increase the number of factories, resulting in a pair of system classes increase, to a certain extent, increase the complexity of the system.

Original address: http://luopq.com/2015/11/10/design-pattern-factory-method/

JavaScript design pattern Theory and Combat: Factory method mode

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.