JavaScript Design Pattern: factory pattern

1. Factory mode

Factory pattern is one of the most common design patterns used to create objects. Without exposing the specific logic of creating objects, encapsulating the logic in a function can be regarded as a factory. Factory patterns can be divided into simple factory, factory method and abstract factory according to the degree of abstraction.

If you only know JavaScript, you may not be able to understand the word abstraction well. Because JavaScript has always regarded abstract as a reserved word and has not been implemented, it is difficult to understand the similarities and differences of the three methods in the factory pattern. So let's talk about the concepts of abstraction and factory through a simple example.

For example, I want to go to a large sporting goods store to buy a basketball, but in addition to basketball, there are football, tennis and other sporting goods in the store. Because I am not familiar with the placement of goods in the store for the first time, it may be difficult to find it in a short time, so I find the salesperson and tell him I want to buy a ball, Then he asked me, "what kind of ball do you want to buy?" I said I wanted to buy a No. 7 basketball. With the help of the salesperson, I soon found the basketball I wanted.

In the above example, the basketball you finally bought can be regarded as an instance object, and the sporting goods store can be regarded as a factory. We can think of it as a function. There are all kinds of sporting goods in this factory function, so how do you get the instance? Because we passed the correct parameter - "Basketball" to the sporting goods store.

When I first told the salesperson my needs, I only said I wanted to buy a ball. He couldn't understand what kind of ball I wanted to buy because I said it too abstractly. The balls I answered are divided into many kinds, but not specific to a certain commodity. This thinking process of extracting one or more common features of complex things is abstraction.

Now that we have understood the concept of abstraction, let's take a look at the three implementation methods of the factory pattern mentioned earlier: simple factory pattern, factory method pattern and abstract factory pattern. Today, I mainly study simple factory and factory methods.

1.1 simple factory mode

Simple factory mode is also called static factory mode. It is decided by a factory object to create an instance of a product object class. It is mainly used to create objects of the same class.

According to the example of instantiating balls in sporting goods stores. The code is as follows:

//Basketball basic class
var Basketball = function(){
    this.intro = 'Basketball is popular in the United States';
}
Basketball.prototype = {
    getMember : function(){
        console.log("Each team needs five players");
    }
}
//Football basic class
var Football= function(){
    this.intro = 'Football is very popular in the world';
}
Football.prototype = {
    getMember : function(){
        console.log("Each team needs 11 players");
    }
}
//Tennis base
var Tennis = function(){
    this.intro = 'Li Na is a top player in Chinese tennis';
}
Tennis .prototype = {
    getMember : function(){
        console.log("Each team needs 1 player");
    }
}
//Sports factory
var SportsFactory = function(name){
    switch(name){
        case 'NBA':
                return new Basketball();
        case 'wordCup':
                return new Football();
        case 'frenchOpen':
                return new Tennis();
    }
}
var basketball = sportsFactory('NBA');
     console.log(basketball);
     console.log(basketball.intro);
     basketball.getMember();

SportsFactory is a simple factory. In this function, there are three constructors corresponding to different sports goods classes. When we call the factory function, we only need to pass one of the three optional parameters NBA, wordcup and frenchopen to obtain the corresponding instance object.

1.2 factory method mode
 

The original intention of the factory method pattern is to postpone the actual creation of objects to subclasses, so that the core class becomes an abstract class. However, it is difficult to create abstract classes in JavaScript like traditional object-oriented. So in JavaScript, we just need to refer to its core idea. We can think of a factory method as a factory class that instantiates an object.

In the simple factory pattern, we need to modify the code two times for each constructor we add. Now we use the factory method pattern to transform the above code. As mentioned just now, the factory method is only regarded as a factory for instantiating objects. It only does the instantiation of objects! We create objects in safe mode.

//Factory method functions created in safe mode
var SportsFactory = function(name){
   if(this instanceof SportsFactory ) {
        var s = new this[name]();
        return s;
  } else {
        return new SportsFactory (name);
  }
}

//Set the constructor of all objects in the prototype of the factory method function
SportsFactory.prototype = {
    Basketball: function() {
        this.intro= "Basketball is popular in the United States"
    },
    Football: function() {
        this.intro = 'Football is very popular in the world';
    }
    Tennis  : function() {
        this.intro = 'Li Na is a top player in Chinese tennis';
    }
}

//call
    var basketball = sportsFactory('Basketball');
    var football= sportsFactory('Football');
    var tennis= sportsFactory('Tennis');


The above code solves the problem that two codes need to be modified every time a constructor is added. If we need to add a new role, we only need to add it in SportsFactory.prototype. For example, we need to add a Pingpang:

SportsFactory.prototype = {
  //....
 Pingpang: function() {
    this.intro= 'China is the world's overlord in the field of table tennis!',    
   
  }
}

//call
var pingpang= SportsFactory('Pingpang');

In the above code, the security mode used may be difficult to understand at one time

var SportsFactory = function(name) {
  if(this instanceof SportsFactory ) {
    var s = new this[name]();
    return s;
  } else {
    return new SportsFactory (name);
  }
}

Because we save constructors such as Basketball, Football and Tennis to SportsFactory.prototype, it means that we must instantiate the SportsFactory function to instantiate the above objects. As shown in the following code.

var SportsFactory = function() {}

SportsFactory .prototype = {
 //...
}

//call
vat factory = new SportsFactory ();
let basketball= new factory.basketball();

In the process of calling the function above, once we forget to use new at any stage, we can't get the basketball object correctly. However, once the security mode is used for instantiation, the above problems can be well solved.

summary

Simple factory mode, also known as static factory method, is used to create an instance of a product object and a single object; The factory method pattern defers the creation of instances to subclasses. In the actual business, we need to select the appropriate mode according to the actual business complexity. For non large front-end applications, flexible use and simple factory can actually solve most problems.

Tags: Javascript ECMAScript

Posted on Wed, 27 Oct 2021 11:48:10 -0400 by regiemon