Singleton mode of JavaScript design pattern-lazy singleton implementation

table of Contents

 

1. Definition

2. Global variables and reduce naming pollution

Use namespace

Use closures to encapsulate private variables

3. General lazy singleton

Encapsulate the logic of the management agent into a function

Usage example (click the button to generate a login pop-up window and display it)

Usage example (list rendering is only bound to one event)


1. Definition

The definition of the singleton pattern is: to ensure that a class has only one instance, and to provide a global access point to access it.

2. Global variables and reduce naming pollution

Global variables are not a singleton mode, but in JavaScript development, we often use global variables as singletons. E.g:

var a = {}; 

a is unique and can be accessed globally, satisfying the definition of singleton mode; however, global variables are prone to naming pollution, and large projects may be overwritten by others at any time. Therefore, the following two methods must be used to relatively reduce the naming pollution caused by global variables:        

  • Use namespace

    var namespace1 = { 
        a: function(){
             alert (1);
        },
        b: function(){
            alert (2);
        }
    };

Define both a and b as attributes of namespace1 to reduce the chance of variables interacting with the global scope.

  • Use closures to encapsulate private variables

    var user = (function () {
        var __name = 'xxx',
            __age = 21;
        return {
            getUserInfo: function () {
                return __name + '-' + __age;
            }
        }
    })();

We use underscores to agree on private variables __name and __age. They are encapsulated in the scope generated by the closure. These two variables cannot be accessed from the outside, which avoids global command pollution.

3. General lazy singleton

Lazy singleton refers to the creation of object instances when needed.

  • Encapsulate the logic of the management agent into a function

    function getSingle(fn) {
        var result; // 在闭包中不销毁
        return function () {
            // 如果result被赋值,则返回;没有则执行创建方法
            return result || (result = fn.apply(this, arguments));
        }
    }
  • Usage example (click the button to generate a login pop-up window and display it)

    // 1.声明创建方法
    var createLoginLayer = function () {
        var div = document.createElement('div');
        div.innerHTML = '我是登录弹窗';
        div.style.display = 'none';
        document.body.appendChild(div);
        return div;
    }
    // 2.传入创建方法返回单例方法,还没创建
    var createSingleLoginLayer = getSingle(createLoginLayer);
    // 3.在需要的时候创建
    document.getElementById('loginBtn').onclick = function () {
        var loginLayer = createSingleLoginLayer();
        loginLayer.style.display = 'block';
    }
  • Usage example (list rendering is only bound to one event)

    var bindEvent = getSingle(function () {
        document.getElementById('div1').onclick = function name() {
            alert('click');
        }
        return true; // 返回true是为了让单例方法不执行||后的创建
    })
    var render = function () {
        console.log('开始渲染列表');
        bindEvent();
    }
    render();
    render();
    render();
    // render函数和bindEvent函数都分别执行了3次,但div实际上只被绑定了一个事件

    Note: The above refers to the excerpted notes of "JavaScript Design Patterns and Development Practices", I strongly recommend that you read the original book!

 

Guess you like

Origin blog.csdn.net/qq_39287602/article/details/108724804