Design pattern list

What’s not linked is what hasn’t been written, what’s planned to be written, Front-end Design Patterns (1) — Factory Pattern Front-end design Pattern (2) — Singleton Pattern Front-end design Pattern (3) — Adapter Pattern Front-end Design Pattern (4) — Decorator Pattern Front-end Design Pattern (5) — Agency Pattern Front-end Design Pattern (6) — Appearance pattern && Observer Pattern Front-end Design Pattern (7) — State and Strategy Pattern Front-end Design Pattern (8) — Prototype pattern…

What is the singleton pattern?

Singleton is to ensure that there is only one instance of a class, the implementation method is generally to determine whether the instance exists, if there is directly return, if not created and return, this ensures that a class has only one instance object. In JavaScript, a singleton acts as a namespace provider, providing a unique point of access to an object from the global namespace.

code

A simple implementation of the singleton pattern

es5

function Window(name) {
    this.name = name;
}
Window.prototype.getName = function () {
    returnthis.name; } / / this is the way to class, can only access through classes, and cannot be accessed through the instance Window. The getInstance = (function () {
    let instance;
    return function (name) {
        if(! instance) { instance = new Window(name); }return instance;
    }
})();

let w1 = Window.getInstance();
let w2 = Window.getInstance();

console.log(w1 === w2) // --> true 
Copy the code

es6


class Window {
    constructor(name) {
        this.name = name;
    }
    static getInstance() {
        if(! this.instance) { this.instance = new Window(); }returnthis.instance; }}let w1 = Window.getInstance();
let w2 = Window.getInstance();
console.log(w1 === w2)
Copy the code

Disadvantages:

  1. The client that uses this class must know that it is a singleton class and must actively call the getInstance method, which is troublesome to use
  2. Does not really prevent clients from directly new Windows
let w3 = new Window();
let w4 = new Window();
Copy the code

The optimization process

Transparent singleton

// Transparent singletonlet Window = (function () {
    let window;
    let Window = function (name) {
        if (window) {
            return window;
        } else {
            this.name = name;
            return(window = this); }}returnWindow; }) ();let w1 = new Window();
let w2 = new Window();
console.log(w1 === w2);
Copy the code
  1. Create a this= null object
  2. The new keyword, if an object is returned, returns the object

But there was a problem: it violated the single responsibility principle and wasn’t clear enough, so it needed to be improved

// Separate the class instance creation logic from the singleton logicfunction Window(name) {
    this.name = name;
}
Window.prototype.getName = function () {
    console.log(this.name);
}


let CreateWindow = (function () {
    let instance;
    return function (name) {
        if(! instance) { instance = new Window(name); }return instance;
    }
})();
let w1 = new CreateWindow('zfpx1');
let w2 = new CreateWindow('zfpx2');
console.log(w1 === w2);
Copy the code

Now it is clear, but there is a small problem, Window is written dead, as a good programmer, must be flexible, to improve.

function Window(name) {
    this.name = name;
}
Window.prototype.getName = function () {
    console.log(this.name);
}


let CreateWindow = (function () {
    let instance;
    return function (name) {
        if(! instance) { instance = new Window(name); }return instance;
    }
})();
let w1 = new CreateWindow('zfpx1');
let w2 = new CreateWindow('zfpx2');
console.log(w1 === w2);
Copy the code

The namespace

1. Variable names conflict

2. Readability requirements for complex hierarchy objects

Before we actually use jquery did not declare all variables on the window, but will hang on $jquery object, and chestnuts two:

$.get();
$.post();
$.ajax();
let$= {ajax() {},get() {},post(){}
}


let$= {}; $.define =function (namespace, fn) {
    let namespaces = namespace.split('. ');
    let fnName = namespaces.pop();
    let current = $;
    for (let i = 0; i < namespaces.length; i++) {
        letnamespace = namespaces[i]; //domif(! current[namespace]) { current[namespace] = {}; //{dom:{}} } current = current[namespace]; } current[fnName] = fn; } $.define('dom.class.addClass'.function () {
    console.log('dom.class.addClass');
});
$.define('dom.attr'.function () {
    console.log('dom.attr');
});
$.define('string.trim'.function () {
    console.log('string.trim'); }); Console. log($) $.dom.class. AddClass ($.dom.class.'title'); // -> dom.class.addClass
$.dom.attr('src'); // -> dom.attr
$.string.trim(' abc '); // -> string.trim

Copy the code

Application scenarios of the singleton mode

jQuery

There will only be one instance of jQuery

if(window.jQuery! =null){return window.jQuery;
}else{
    //init~~~~~~~
}
Copy the code

The modal window

General website will have user system, for example, we go to Taobao to buy things, the first time you need to log in first

<! DOCTYPE html> <html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button id="show-btn"> Display login box </button> <button id="hide-btn"</button> <script> class Login {constructor() {
                this.element = document.createElement('div'); This.element.innerhtml = (' user name <input name="username"/> Password <input name="password"/>
                     <input type="submit" value="Login"/ > `); this.element.style.cssText = `width:100px; height:100px; position:absolute; left:50%; top:50%; margin-top:-50px; margin-left:-50px; display:none`; document.body.appendChild(this.element); }show() {
                this.element.style.display = 'block';
            }
            hide() {
                this.element.style.display = 'none';
            }
            static getInstance() {
                if(! this.instance) { this.instance = new Login(); }return this.instance;
            }
        }
        document.getElementById('show-btn').addEventListener('click'.function () {
            Login.getInstance().show();
        });
        document.getElementById('hide-btn').addEventListener('click'.function () {
            Login.getInstance().hide();
        });
    </script>
</body>

</html>
Copy the code

store

Redux has only one repository for the entire application and only one state for the repository

// Redux has only one repository for the entire application, and the repository has only one statefunction createStore(reducer) {
    let state;
    let listeners = [];
    function subscribe(listener) {
        listeners.push(listener);
    }
    function getState() {
        return state;
    }
    function dispatch(action) {
        state = reducer(state, action);
    }
    return {
        getState,
        dispatch,
        subscribe
    }
}

let reducer = function() {}let store = createStore(reducer);
Copy the code

Today to write here, like can thumbs up, at the same time welcome to throw turn, have time to write down the summary ~