preface

Recently, I have been reading javascript design patterns and development practices. Although I have seen some of them before, I forgot 7788 because of the lack of records. This time, I should take a good look at them and remember them well

What is the singleton pattern

So let’s look at the definition.

Ensure that a class has only one instance and provide a global access point to access it.

Single example patterns in reality

function Card(money) {
    this.money = money;
}
Card.prototype.getMoney = function(){
    console.log(this.money);
}
const card = new Card(500);
card.getMoney(); / / 500
Copy the code

But after a while, Xiao Ming forgot where the card was, so he had to apply for another card, wasting another 500 yuan.

function Card(money) {
    this.money = money;
}
Card.prototype.getMoney = function(){
    console.log(this.money);
}
const card = new Card(500);
card.getMoney(); / / 500
const card2 = new Card(500);
card2.getMoney(); / / 500
console.log(card === card2); //false
Copy the code

Xiao Ming only needs one membership card, but he has two, which is a waste of resources. Moreover, the hair salon is not good enough. The information of the card should be recorded according to the mobile phone number or ID card.

Later, the boss asked the technical staff xiaoqiang to introduce a new system, which can judge whether you have a card, and if you have, you can directly use the card that has been done. At this time, the singleton mode is used. I’m not afraid to lose my membership card anymore.

const Card = (function () {
    let instance;
    return function Card(money) {
        if (instance) returninstance; ,// You already got your card
        this.money = money;
        instance = this;
    }
})()
Card.prototype.getMoney = function () {
    console.log(this.money);
}
const card = new Card(500);
card.getMoney(); / / 500
const card2 = new Card(500); // No, you still have 500 yuan from your last card
card2.getMoney(); / / 500
console.log(card === card2); //true
Copy the code

There are some small bugs in this system. Before helping customers to apply for cards, you must click “new”, otherwise there will be mistakes. The clerk always forgets, resulting in the loss of many customers’ data

const Card = (function () {
    let instance;
    return function Card(money) {
        if (instance) return instance;
        this.money = money;
        instance = this;
    }
})()
Card.prototype.getMoney = function () {
    console.log(this.money);
}
const card = Card(500);
card.getMoney(); //Uncaught TypeError: Cannot read property 'getMoney' of undefined
// Where is my money?
Copy the code

Behind again looked for technical personnel small strong to help make once.

const Card = (function () {
    let instance;
    return function Card(money) {
        if(! (this instanceof Card)) throw("New! I don't remember to deduct my pay."); // You can also return new Card(money)
        if (instance) return instance;
        this.money = money;
        instance = this;
    }
})()
Card.prototype.getMoney = function () {
    console.log(this.money);
}
const card = Card(500);
card.getMoney(); 
Copy the code

If the shop assistant does not remember to click new and help the customer to apply for the membership card, there will be a pop-up error. This stability

General singleton

Technical personnel small strong because received hair salon project, earn a little money, and more and more businesses look for small strong to make a system, small strong do not want to move bricks in the company 996. But there are too many businesses, simply busy, please people want to share a cup of soup. What can we do? So Jack Bauer improved the system again

const superCard = function(fn){
    if(Object.prototype.toString.call(fn) ! = ="[object Function]")throw "Please pass the function correctly.";
    let instance;
    return function superCard(. params){
        if(! (this instanceof superCard))throw Please click "new";
        returninstance? instance:instance =new fn(...params);
    }
}
Copy the code

Take the logic out of the card and encapsulate it, and you can use it in any store, whether you’re a barbershop, a convenience store or a foot wash.

const superCard = function(fn){
    if(Object.prototype.toString.call(fn) ! = ="[object Function]")throw "Please pass the function correctly.";
    let instance;
    return function superCard(. params){
        if(! (this instanceof superCard))throw Please click "new";
        returninstance? instance:instance =new fn(...params);
    }
}

const Barber = function(money){
    this.money = money;
}
Barber.prototype.getMoney = function(){
    console.log(this.money);
}
const SuperBarber = superCard(Barber);
const card = new SuperBarber(500);
const card2 = new SuperBarber(500);
card.getMoney(); / / 500
card2.getMoney(); / / 500
console.log(card === card2); //true
Copy the code

Now xiaoqiang has achieved wealth freedom, win baifumei, onto the peak of life……

Applications in the front end

Back to the front end, because JS is a classless language, all classes are trying to copy out, creating objects in JS is very simple, so the simplest simple mode is to create a global variable, unique, global can access the object. However, the use of global variables should be reduced. We can reduce the use of global variables through namespaces and private variables.

The namespace

var MyApp = {};
MyApp.namespace = function (name) {
    var parts = name.split('. ');
    var current = MyApp;
    for (var i in parts) {
        if (!current[parts[i]]) {
            current[parts[i]] = {};
        }
        current = current[parts[i]];
    }
};
MyApp.namespace('event');
MyApp.namespace('dom.style');
Copy the code

Private variables

var user = (function () {
    var __name = 'sven',
        __age = 29;
    return {
        getUserInfo: function () {
            return __name + The '-'+ __age; }}}) ();Copy the code

The singleton pattern in VUEX

The singleton pattern is used to ensure that a vue instance is installed only once

The react state management is unique to the Store in Redux, and all components have a way to interact with it. For example, the common dialog box and status bar of front-end page are basically a singleton mode, and only one is needed globally. These are all examples of the singleton pattern