几种用JavaScript实现的单例模式(Singleton Design Pattern)

<html>
<script>

var Singleton = function() { 
 var attr = 1, fn = function(){ console.log("I am executed in closure");}; 
 return { 
   method : function(){ fn(); }, 
   getAttr : function(){ console.log("will be returned: " + attr ); return attr; } 
 }; 
}(); 

Singleton.method(); 
Singleton.getAttr(); 


var LazySingleton = function(){ 
var attr = 2, fn = function(){ console.log("I am LazySingleton function");}; 
var obj = { 
method : function(){ fn(); }, 
getAttr : function(){ return attr; } 
}; 
function init(){ 
return obj; 
} 
return { getInstance: init}; 
}(); 


LazySingleton.getInstance().method(); 
console.log("LazySingleton: " + LazySingleton.getInstance().getAttr()); 

function Universe() {

    if (typeof Universe.instance === 'object') {
        return Universe.instance;
    }

    this.start_time = 0;
    this.bang = "Big";

    Universe.instance = this;
    // return this implicitly
}

// test
var uni = new Universe();
var uni2 = new Universe();
console.log(uni === uni2); // true

function Universe2() {
    // instance cached
    var instance = this;

    this.start_time = 0;
    this.bang = "Big";
    Universe2 = function () {
        return instance;
    };
}

var un1i = new Universe2();
var un1i2 = new Universe2();
un1i.bang = "123";
console.log(un1i === un1i2); // true
console.log(un1i2.bang); // 123

var Universe3;
(function () {
    var instance;
    Universe3 = function Universe3() {
        if (instance) {
            return instance;
        }
        instance = this;

        this.start_time = 0;
        this.bang = "Big";
    };
} ());

var a = new Universe3();
var b = new Universe3();
alert(a === b); // true
a.bang = "123";
alert(b.bang); // 123

</script>
</html>
汪子熙 CSDN认证博客专家 前端框架 Node.js SAP
JerryWang,2007年从电子科技大学计算机专业硕士毕业后加入SAP成都研究院工作至今。Jerry是SAP社区导师,SAP中国技术大使。2020年5月下旬,Jerry做了脑部肿瘤的开颅切除手术,对编程和人生又有了新的感悟。
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 博客之星2020 设计师:CY__0809 返回首页