单例模式
es6
// 浏览器window就是一个典型的单例模式
class Window {
constructor(name) {
this.name = name; 私有属性,即不能通过new Window创建实例
}
static getInstance(name) {// 可以Window类的静态方法拿到实例
if (!this.instance) {
this.instance = new Window(name);
}
return this.instance;
}
}
var w1 = Window.getInstance();
var w2 = Window.getInstance();
console.log(w1 === w2);
es5
let Window = function(name) {
this.name=name;
}
Window.prototype.getName=function () { // 实例的方法
console.log(this.name);
}
Window.getInstance=(function () { // 类上的方法,可以通过类来访问,而不能通过实例访问
let window=null;
return function (name) {
if (!window)
window=new Window(name);
return window;
}
})();
let window=Window.getInstance('zfpx');
window.getName();
//这样的写法存在两个问题
/*
客户端,就是主动调用者必须知道这是一个单例的类,必须主动调用getInstance
并不能真正阻止客户端new这个类
解决:
1. 可以直接new ,但是它还是单例的(透明单例)
*/
透明单例
let Window=(function () {
let window;
let Window=function (name) {
if (window) {
return window;
} else {
this.name=name;
return (window=this);
}
}
Window.prototype.getName=function () {
console.log(this.name);
}
return Window;
})();
let window1=new Window('zfpx');
let window2=new Window('zfpx');
window1.getName();
console.log(window1 === window2)
单例与构建分开
function Window(name) {
this.name=name;
}
Window.prototype.getName=function () {
console.log(this.name);
}
let createSingle=(function () {
let instance;
return function (name) {
if (!instance) {
instance=new Window();// 存在问题:写死了,如果需要创建一个新的类,这这个方法需要载写一份
}
return instance;
}
})();
//////////////
function Dialog(name) {
this.name=name;
}
let createSingle=(function () {
let instance;
return function (name) {
if (!instance) {
instance=new Dialog();// 存在问题:写死了,如果需要创建一个新的类,这这个方法需要载写一份
}
return instance;
}
})();
let window1=new createSingle('zfpx');
let window2=new createSingle('zfpx');
window1.getName();
console.log(window1 === window2)
function Window(name) {
this.name=name;
}
Window.prototype.getName=function () {
console.log(this.name);
}
let createSingle=function (Constructor) {
let instance;
return function () {
if (!instance) {
Constructor.apply(this,arguments);
//this._proto_ = Constructor.prototype
Object.setPrototypeOf(this,Constructor.prototype)
instance=this;
}
return instance;
}
};
let CreateWindow=createSingle(Window);
let window1=new CreateWindow('zfpx');
let window2=new CreateWindow('zfpx');
window1.getName();
console.log(window1 === window2)