單例設計模式:保證一個類僅有一個實例,而且提供一個訪問它的全局訪問點。有些對象只須要一個,這時可用單例模式。javascript
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
複製代碼
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);
複製代碼
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);
複製代碼
let MyApp = {
name:'app',
getName:function() {
console.log(this.name);
}
};
let MyApp2 = (function(){
var _name = 'app';
return {
getName:function() {
console.log(_name);
}
}
})();
複製代碼
var createA = (function () {
var instance;
return function () {
if(!instance){
//xxx
instance = 'A';
}
return instance;
};
})();
function render() {
createA();
console.log('b');
}
render();
render();
複製代碼
var createB = (function () {
var instance;
return function () {
if(!instance){
//xxx
instance = 'B';
}
return instance;
};
})();
複製代碼
function getSingleton(fn) {
var result;
return function() {
return result||(result = fn.apply(this,arguments));
}
}
var createA = function () {
var instance;
if(!instance){
//xxx
instance = 'A';
}
return instance;
};
var createB = function () {
var instance;
if(!instance){
//xxx
instance = 'B';
}
return instance;
};
var createASingle = getSingleton(createA);
var createBSingle = getSingleton(createB);
function render() {
createASingle();
createBSingle();
}
render();
render();
複製代碼
單例模式用到了閉包和高階函數的特性。單例模式是簡單但經常使用到的模式,好比單頁應用、websocket鏈接等等。特別是惰性單例模式,用到時才建立,再次用到是不須要再次建立。建立對象和管理單例的職責分佈在不一樣的方法中,方便擴展和管理。java