1024programmer JavaScript Singleton mode of JavaScript design pattern

Singleton mode of JavaScript design pattern

Preface


In the course of Javascript development, the pioneers have summed up many solutions to specific problems from practice. Simply put, a design pattern is a concise and elegant solution to a specific problem on a certain occasion

In the future, I will record various common design patterns in Javascript. Maybe you are already familiar with it, maybe you are already using it, but you are not particularly familiar with its concept, or maybe you just have some vague concepts about it. Well, I believe this series will definitely bring you some gains

Before understanding these common modes, by default you have at least mastered

  • this

  • closure

  • higher order function

  • Prototype and prototype chain

Understanding them will give you a clearer understanding of a pattern. Of course, maybe the things I recorded about this aspect before can give you some help. Portal

If there are any mistakes or mistakes in the article, please give advice to the friends who have seen it, thank you in advance

Below, let’s start with it — the singleton pattern

Concept

As the name suggests, there is only one instance

Definition: Ensure that a class has only one instance, and provide a global access point to access it

Seeing such a definition, whether in your mind The concept of global variables will emerge. It is undeniable that global variables conform to the concept of singleton mode. However, we generally don’t and shouldn’t use it as a singleton for two reasons:

  • Global Naming pollution

  • It is not easy to maintain and is easily overwritten

Before ES6, we usually use a constructor To simulate a class, now we can also directly use the class keyword to create a class, although its essence is also a prototype

To ensure that a class has only one instance, we need to provide a variable to indicate whether the current An instance of a class has already been created. Therefore, the core of the singleton mode is: Ensure that there is only one instance and provide global access

Around this core, we basically understand the implementation of the singleton mode p>

Implementation


Basic version

According to the definition of singleton mode, we can use Simple implementation in the following way

var Singleton = function(name){
   this.name = name
 }

 Singleton.instance = null // Initialize a variable Singleton.getInstance = function(name) {// Determine whether this variable has been assigned a value, if not, make it the instantiated object of the constructor // If it has been assigned, directly  return
   if(!this. instance) {
    this. instance = new Singleton(name)
    }
   return this. instance
 }
 var a = Singleton. getInstance('Tadpole')
 var b = Singleton. getInstance(& # 39; Amy & # 39;)
 a === b // true

The code above clearly reflects the definition of the singleton pattern. Through an intermediate variable, only one instance is initialized, so a and b are completely equal in the end

We can also use the ES6 class keyword to achieve

class Singleton {
     constructor(name){
         this.name = name
       this. instance = null
   }
   // Provide an interface to instantiate the class
     static getInstance(name) {
         if(!this. instance) {
           this. instance = new Singleton(name)
       }
       return this. instance
    }
 }

It is not difficult to find that the implementation of ES6 is basically the same as our implementation through the constructor

There is a problem:

  • It is not transparent enough, we need to constrain the calling method of class instantiation

  • The coupling is too high, and the functional business code is coupled together Not conducive to later maintenance

Constructor

Let’s make a simple modification to the above method

// hang the variable directly on the constructor, and finally return it
   function Singleton(name) {
      if(typeof Singleton. instance === 'object'){
         return Singleton. instance
      }
      this.name = name
       return Singleton. instance = this
  }
  // create instance normally
 
  var a = new Singleton('Tadpole')
  var b = new Singleton('Amy')

It solves the problem that the basic version of the class is not transparent enough, you can use the new keyword to initialize the instance, but there are also new problems

  • If you judge the type of Single.instance to return, you may not get the expected result

  • coupling too high

This method can also be implemented by ES6

// Rewrite the constructor as a singleton  schema constructor
 class Singleton {
 constructor(name) {
     this.name = name
     if(!Singleton. instance) {
        Singleton. instance = this
     }
     return Singleton. instance
   }
 }

Closure

Through the definition of singleton mode, we want to ensure that there is only one instance and provide global access. Then, closures can certainly meet such requirements

var Singleton = (function () {
 var SingleClass = function () {};
 var instance;
 return function () {
  if (!instance) {
     instance = new SingleClass() // If it does not exist, then a new one
  }
  return instance;
 }
 })()

Through the characteristics of closure, save a variable and finally return it, providing global access

Similarly, the above code still does not solve the problem of coupling degree

Let’s take a closer look at this piece of code. If we extract the part of the constructor to the outside, will the separation of functions be achieved?

Proxy implementation

Modify the code above

function Singleton(name) {
  this.name = name
 }
 var proxySingle = (function(){
   var instance
   return function(name) {
     if(!instance) {
       instance = new Singleton(name)
     }
   return instance
  }
 })()

The step of creating a function is extracted from the function, and the logic responsible for managing the singleton is moved to the proxy class proxySingle. The purpose of this is to turn the Singleton class into an ordinary class, in which we can write some business logic separately to achieve the effect of logical separation

We have now achieved the effect of logical separation, And it’s not transparent anymore. However, does the class responsible for the proxy fully meet our requirements? The answer is no. Imagine, if our constructor has multiple parameters, should we also reflect it in the proxy class?

So, is there a more general way to achieve it?

General lazy singleton

In the previous rounds, we have basically completed the creation of the singleton mode. Now, we need to find a more general way to solve the problems left before

Imagine if we use the function as a parameter

// pass the function as a parameter
 var Singleton = function(fn) {
    var instance
    return function() { // Collect parameters through apply and execute the passed parameters to return the result
      return instance || (instance = fn. apply(this, arguments))
    }
 }

The biggest advantage of this method is that it is equivalent to caching the result we want, and calling it when we need it, which conforms to the single responsibility of encapsulation

Application

As I said before, all the patterns are summarized from practice, let us see what applications it has in actual development

Through the definition of singleton mode, it is not difficult to think of its use in actual development, such as: global mask layer

It is impossible for us to call a global mask layer every time Create it all, the best way is to let it be created only once, then save it with a variable, and return the result directly when it is called again

The singleton mode is very suitable for us Requirements

// simulate a mask layer var createDiv = function () {
         var div = document. createElement('div')
     div.style.width = '100vw'
     div.style.height = '100vh'
     div.style.backgroundColor = 'red'
     document.body.appendChild(div)
     return div
 }// Create this element var createSingleLayer = Singleton(createDiv)document.getElementById('btn').Onclick= function () { // Only displayed when called
     var divLayer = createSingleLayer()
 }

Of course, there are still many applicable scenarios in practical applications, such as the login box, and state management tools such as Vux that we may use. They actually all fit the singleton mode The

postscript

The singleton mode is a simple and practical mode. Through the two methods of creating objects and managing singletons, we will Many useful and elegant applications can be created. Of course, it also has its own shortcomings, such as only one example~

Rational use can exert its greatest power

Finally, I recommend a wave of front-end learning process, interested friends You can click here, or you can scan the QR code below to follow my WeChat official account, view more content in the past, welcome star attention

Recommended tutorial: “JS Tutorial”

The above is the Javascript design pattern For more details about the singleton mode, please pay attention to other related articles on 1024programmer.com!

Friends of �� can click here, or scan the QR code below to follow my WeChat official account, view more content in the past, welcome star attention

Recommended tutorial: “JS Tutorial”

The above is the detailed content of the singleton mode of the Javascript design pattern. For more information, please pay attention to other related articles on 1024programmer.com!

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/singleton-mode-of-javascript-design-pattern/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索