其他分享
首页 > 其他分享> > [干货]设计模式:六种单例的创建方式,上岸蚂蚁金服

[干货]设计模式:六种单例的创建方式,上岸蚂蚁金服

作者:互联网


function Singleton(name) {

    this.name = name;

}

Singleton.getInstance = function (name) {

    if(this.instace){

        return this.instace;

    }else {

        this.instace = new Singleton(name);

        return this.instace;

    }

};

var a = Singleton.getInstance('a');

var b = Singleton.getInstance('b');

console.log(a===b); //true 

5."透明"的单例模式

var instace;

function Person(name) {

    this.name = name;

    if (!instace) {

        instace = this;

    }

    return instace;

}



Person.prototype.getName = function () {

    console.log(this.name);

};

var a = new Person('a');

var b = new Person('b');

console.log(a===b); 

6.代理模式创建单例模式

function Person(name) {

    this.name = name;

}

Person.prototype.getName = function () {

    console.log(this.name);

};

var CreateSinglePerson = (function (name) {

    var instance;

    return function () {

        if (!instance) {

            instance = new Person(name);

        }

        return instance;

    };

})();

var a = new CreateSinglePerson('a');

var b = new CreateSinglePerson('b');

console.log(a === b);

var c = new Person('c');

var d = new Person('d');

console.log(c === d); 

JavaScript中的单例模式


let MyApp = {

  name:'app',

  getName:function() {

    console.log(this.name);

  }  

};

let MyApp2 = (function(){

    var _name = 'app';

    return {

        getName:function() {

            console.log(_name);

        } 

    }

})(); 

#####惰性单例