JS中的单例模式及单例模式原型类的实现

时间:2021-07-11
本文章向大家介绍JS中的单例模式及单例模式原型类的实现,主要包括JS中的单例模式及单例模式原型类的实现使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

单例模式

单例模式的定义: 保证一个类只有一个实例,并提供一个访问它的全局访问点

通过一个简单的例子来了解单例模式的作用:

class Div {
    constructor() {
        return document.createElement("div");
    }
}

btn.addEventListener("click", function (event) {
    const div = new Div();
    document.body.appendChild(div);
});

现在页面上的这个按钮每被点击一下就会生成一个div,但是现在如果这个div是登录框,我当然就会想要这段函数只生成一个,这时候就可以用到单例模式的思想:让一个类只会生成一个实例。

在JS里实现单例模式很简单,只要使用闭包就能做到,这是使用ES6的class语法实现的单例模式:

let div = null;
class Div {
    constructor() {
        return div ?? (div = document.createElement("div"));
    }
}

这样,通过闭包实现了单例模式,无论点击多少次按钮,只会生成一个div。

考虑到单例模式应用的广泛,我实现了一个原型类,通过继承该原型类可以直接得到一个单例模式的类:

const SingletonConstructor = (function () {
    const instances = {};
    return class {
        constructor(Constructor) {
            let className = new.target.name;
            if (instances[className]) {
                return instances[className];
            } else {
                let instance = new Constructor();
                Object.setPrototypeOf.call(null, instance, new.target.prototype);
                return (instances[className] = instance);
            }
        }
    };
})();

class Div extends SingletonConstructor {
    constructor() {
        super(function () {
            return document.createElement("div");
        });
    }
}

需要设计为单例的类只需要继承这个原型类后在构造函数的super中写入构造函数就能实现单例模式。

原文地址:https://www.cnblogs.com/shaddollxz/p/14999722.html