单例模式

1.单例模式

let SingleInstance = (function (){
    let instance = null;  //这里使用了“闭包”,为SingleInstance保存一个私有的instance变量
    return function (name){
        if(instance){
            return instance;
        }
        this.name = name;
        instance = this;
    }
})(); //这里使用的是立即调用函数,因此实际上是将返回的匿名函数赋予了SingleInstance,instance变量链接到它的作用域链上

let p = new SingleInstance("Tom");
console.log(p); //输出的是Objet类型

 

  可以看到,输出类型并不是我们想要的某个特定类型,因为我们的构造函数本体是一个匿名函数,浏览器是无法识别这个构造函数的类型的。

 

2.代理版单例模式

function  SingleInstance(name){
    this.name = name;
}
SingleInstance.prototype.getName = function (){
    return this.name;
}

let ProxySingleInstance = (function (){
    let instance = null;
    return function (name){
        if(instance){
            return instance;
        }
        return instance = new SingleInstance(name);
    }
})();

let p = new  ProxySingleInstance("Tom");
console.log(p); //输出SingleInstance类型
console.log(p.getName()); //输出"Tom"

  代理版单例模式将对象创建和实例判断分离开来,SingleInstance只负责对象的创建,ProxySingleInstance只负责判断实例是否存在。

posted @ 2022-03-15 16:27  ˙鲨鱼辣椒ゝ  阅读(27)  评论(0)    收藏  举报