Design pattern knowledge extraction will be divided into N articles, this article is the first article, later will carry out other related synchronization (will share, will not torture), aimed at improving skills, better enjoy the pleasure of typing ~

define

The singleton pattern ensures that a class has only one instance and provides a global access point to access it. The implementation method checks whether the instance exists first and returns if it does, and creates and returns if it does not. This ensures that a class has only one instance object.

Usage scenario: a single object. For example, popovers should only be created once, no matter how many times they are clicked.

For example:

class CreateUser {
    constructor(name) {
        this.name = name;
        this.getName();
    }
    getName() {
        return this.name; }}// The proxy implements the singleton pattern
var proxyMode = (function() {
    var instance = null;
    return function(name) {
        if(! instance) { instance =new CreateUser(name);
        }
        return instance;
    }
})();

// Test the singleton pattern
var a = proxyMode('aaa');
var b = proxyMode('bbb');
Since the singleton pattern is instantiated only once, the following instances are equal
console.log(a === b); // true
// Print a,b and the name of the object
console.log(a.name); // aaa
console.log(b.name); // aaa
Copy the code

The above is about some singleton mode principle, let’s use this mode to realize the popover function.

Implement a popover

Show you the code directly:

<button id="btn1">Click me to create a new window</button>
<button id="hide">Let me hide</button>
Copy the code
.common-box {
    background: rgb(233, 90, 90);
    width: 100px;
    height: 100px;
    overflow: hidden;
}
Copy the code
const btn1 = document.querySelector('#btn1');
const createWindow = (() = > {
    let div = null;
    return (words) = > {
        if(! div) { div =document.createElement('div');
            div.innerHTML = words || 'I am the default statement';
            div.className = 'common-box';
            div.style.display = 'none';
            document.body.appendChild(div);
        }
        
        return div;
    }
})();   

btn1.addEventListener('click', () = > {let box = createWindow('content');
    box.style.display = 'block';
}, false);

/ / hide
document.querySelector('#hide').addEventListener('click', () = > {document.querySelector('.common-box').style.display = 'none';
}, false);
Copy the code

The effect is as follows:

Reference and postscript

  • Juejin. Cn/post / 684490…

  • www.jianshu.com/p/e1ed20a1a…

Read more about escape here 🙂