Javascript-設計模式之單例模式


/**
* 單例模式一
* 個人更傾向這種,代碼簡介
*/
var Singleton = (function(){
var instantiated;
function init(){
/*singleton code here*/
return {
publicMethod: function(){
console.log('hello world');
},
publicProperty: 'test'
};
}

return {
getInstance: function(){
if (!instantiated) {
instantiated = init();
}
return instantiated;
}
};
})();

/*calling public methods is then as easy as:*/
Singleton.getInstance().publicMethod();

/**
* 單例模式二
*/
var SingletonTester = (function(){

//args: an object containing arguments for the singleton
function Singleton(args){

//set args variable to args passed or empty object if none provided.
var args = args || {};
//set the name parameter
this.name = 'SingletonTester';
//set the value of pointX
this.pointX = args.pointX || 6; //get parameter from arguments or set default
//set the value of pointY
this.pointY = args.pointY || 10;

}

//this is our instance holder
var instance;

//this is an emulation of static variables and methods
var _static = {
name: 'SingletonTester',
//This is a method for getting an instance

//It returns a singleton instance of a singleton object
getInstance: function(args){
if (instance === undefined) {
instance = new Singleton(args);
}
return instance;
}
};
return _static;
})();

var singletonTest = SingletonTester.getInstance({
pointX: 5
});
console.log(singletonTest.pointX); // outputs 5

發佈了40 篇原創文章 · 獲贊 1 · 訪問量 1653
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章