定義:保證一個類僅有一個實例,并提供一個訪問它的全局訪問點。
單例模式是一種常用的模式殊鞭,有些對象往往只需要一個,比如:線程池像云、全局緩存、瀏覽器中的 window 對象等。在 Javascript 開發(fā)中,單例模式的用途同樣非常廣泛顶霞,比如做登錄彈框,它在當前頁面是唯一的锣吼,無論單擊多少次,都只會創(chuàng)建一次蓝厌,這就非常適合用單例模式來創(chuàng)建玄叠。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let p1 = new Person();
let p2 = new Person();
console.log(p1 === p2);//fasle
1.簡單實現(xiàn):
class Person {
constructor(name, age) {
console.log('person created');
}
}
//創(chuàng)建Person的工作提前了入
const person = new Person();
export { person }
缺點:創(chuàng)建實例提前了,通用性差
2.優(yōu)化上面的方法
class Person {
constructor(name, age) {
console.log('person created');
}
//靜態(tài)是屬性
static ins = null;
static getInstance(args) {
if (!this.ins) {
this.ins = new Person(...args);
}
return this.ins;
}
}
export { Person }
使用:
import { Person } from "./Person.js";
let p1 = Person.getInstance("張三", 18);
let p2 = Person.getInstance("李四", 19);
let p3 = new Person("李四", 19);
console.log(p1 === p2);//true
console.log(p1 === p3);//false
缺點:由于js沒有private關(guān)鍵字,無法將構(gòu)造函數(shù)私有化,這也就需要使用者知道調(diào)用getInstance方法創(chuàng)建實例,而不是通過new的方式創(chuàng)建實例
再次優(yōu)化:
singleton.js
export function singleton(className) {
let ins;
return class {
constructor(...args) {
if (!ins) {
ins = new className(...args);
}
return ins;
}
}
}
person.js
import { singleton } from "./singleton.js";
class Person {
constructor(name, age) {
console.log('person created');
}
}
const newPerson = singleton(Person);
export { newPerson as Person }
使用:
import { Person } from "./Person.js";
let p1 = new Person("張三", 18);
let p2 = new Person("張三", 18);
//這里的new 相當于 new 的singleton里return的class
console.log(p1 === p2);
缺點:
import { Person } from "./Person.js";
let p1 = new Person("張三", 18);
let p2 = new Person("張三", 18);
Person.prototype.play = function () {
console.log("加在原型上的方法--play");
}
p1.play();//報錯TypeError: p1.play is not a function
console.log(p1 === p2);
上面Person指向的是 singleton中return 的class
而p1,p2是Person的實例,所以p1,p2無法使用掛載在singleton中return 的class原型上的方法.
使用代理來實現(xiàn)單例:
export function singleton(className) {
let ins;
//使用代理來攔截construct
return new Proxy(className, {
construct(target, args) {
if (!ins) {
ins = new target(...args);
}
return ins;
}
})
}
代理實現(xiàn)單例.png