Javascript design patterns theory and programming practice of simple factory patterns

  • 2020-09-28 08:45:38
  • OfStack

Read the directory

Basic introduction
For example
Conclusion shows that

The simple factory pattern is a method that determines which instance of a class to create, and these instances often have the same interface. This pattern is mainly used in cases where the type being instantiated is not determined at compile time, but is determined at execution time. In layman's terms, it's like the soda machine in the office coffee or milk depending on which button you press.

The simple factory pattern is also useful when creating ajax objects.

The most common way to create objects is to use the new keyword to call constructors, which results in dependencies between objects. The factory pattern is a design pattern that helps eliminate dependencies between classes by using a method to determine which class to instantiate. This paper introduces the theory of simple factory pattern in detail and illustrates its application with examples.

Basic introduction

The simple factory pattern is one of the most basic factory patterns. Instantiate a specific product class based on parameters by defining a factory class.

For example

Let's take an example to illustrate: suppose we develop a tourism industry website, which sells products such as air tickets and hotels. One user is going to buy a plane ticket. We can define the relevant classes as follows:


 var productEnums = {
   flight: "flight",
   hotel: "hotel"
 };
 function Flight() {
   console.log("This is Flight");
 }
 function Hotel() {
   console.log("This is Hotel");
 }
 function User() {
   this.shopCart = [];
 }
 User.prototype = {
   constructor: User,
   order: function (productType) {
     var product = null;
     switch (productType) {
       case productEnums.flight:
         product = new Flight();
       case productEnums.hotel:
         product = new Hotel();
       default:
     }
     this.shopCart.push(product);
   }
 }
 var user = new User();
 user.order(productEnums.flight);

This code defines three classes: user class User, airline class Flight, and hotel class Hotel, where User contains the reservation method. The user can directly pass in the product type when booking. This code looks fine at first glance, but requirements and business are constantly changing. If the company expands and adds visa business, we need to modify the User class to ensure that it supports visa. We could do that, of course, but what's wrong with just modifying the User class? Is there a better way?

The first thing to mention is the User class, which represents the user class, and the user class is essentially unrelated to a specific type of business. In other words, the business may increase at any time, but the user's code on the business aspect is to create the product order. New visa business nature and there is no difference between existing ticket and hotel, if going to modify User increases by + 1 every kind of business classes, it's bad for code stability and maintainability greatly, there is a better solution dedicated to create the order class in different business management, this class is a simple plant.

We modify the code as follows:


var productFactory = (function () {
   var productFactories = {
     "flight": function () {
       return new Flight();
     },
     "hotel": function () {
       return new Hotel();
     }
   };
   return {
     createProduct: function (productType) {
       return productFactories[productType]();
     }
   }
 })();
 User.prototype = {
   constructor: User,
   order: function (productType) {
     this.shopCart.push(productFactory.createProduct(productType));
   }
 }

There are two main changes to this code:

(1) One product factory was added, and different objects were returned according to different product types

(2) Modify the order method of the User class to invoke the create product method in the factory class.

The benefits are:

(1) Make User's order method more focused, only doing the function of product reservation, while extracting and creating product orders into the specialized factory class, the code is more concise and clear

(2) An factory specially manages product. It is easy to add new products without modifying the User class

Conclusion shows that

The main feature of the simple factory pattern is that it separates the creation and use of objects, which are mainly composed of three parts:

1. Objects use classes, which are consumers created by the factory, independent of the type of objects and the creation process

2. Factory class. The factory class creates different objects according to the passed parameters and returns to the object use class, including the creation process of different objects

3. Object class: different types of products produced by different businesses are products produced by the factory

Advantages of the simple factory model

1. The factory class centralizes the creation of all objects, facilitating the unified management of object creation

2. The consumer of the object simply USES the product and implements the single 1 responsibility

3. Easy to expand. If a new business is added, only the relevant business object class and the method of producing the business object in the factory class need to be added, and there is no need to modify other places.

Applicable scenario

1. Different instances need to be generated according to different parameters, and these instances have some common scenes

2. Users only need to use the product and do not need to know the creation details of the product

Note: Unless the scenario is applicable, you should not abuse the factory pattern, which can cause code complexity.


Related articles: