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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值