js singleton


单例模式

只允许实例化一次的对象类,我们不需要每次都实例化一次,使用的都是同一个对象

这个特性在从单个中心位置协调系统范围的行动的情况下非常有用

单例模式减少了对全局变量的需求,限制了命名空间污染和名称冲突的相关风险

例如数据库连接池,管理整个应用程序的所有数据库连接的创建、销毁和生存期,确保不会"丢失"任何连接。

模块模式是 JavaScript 对单例模式的体现。

Example

let Singleton = (()=>{
    let _instance = null;
    //一个待实例化的类
    function _module(){
        this.name = 'xxx';
        this.callLeader = ()=>{
            return 'The Leader Is ' + this.name;
        }
        this.setLeader = (name) => {
            this.name = name;
        }
    }

    return {
        getInstance:()=>{
            if(!_instance){
                _instance = new _module();
            }
            return _instance;
        }
    }
})();

let instance1 = Singleton.getInstance()
let instance2 = Singleton.getInstance()

console.log(instance1 === instance2) // true

相关