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

posted @   王猪猴  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示