Open weikee94 opened 2 years ago
class SingleObject {
// 这里的login 不是静态的
// 因为每次初始化,这个都会存在每个instance 里
login() {
console.log("login");
}
}
// getInstance 这个就是静态,因为它被挂载到SingleObject 上
// 所以无论new 多少次,只会有一个
SingleObject.getInstance = (function () {
let instance;
return function () {
if (!instance) {
instance = new SingleObject();
}
return instance;
};
})();
// test
// 注意⚠️这里使用静态函数 getInstance, 不能 new SingleObject();
let obj1 = SingleObject.getInstance();
obj1.login();
let obj2 = SingleObject.getInstance();
obj2.login();
console.log("obj1 === obj2 ", obj1 === obj2);
console.log("--------Divider----------");
let obj3 = new SingleObject();
obj3.login();
console.log("obj1 === obj3", obj1 === obj3);
class LoginForm {
private state: string = 'hide' // 'hide' / 'show'
private constructor() {}
show() {
if (this.state === 'show') {
console.log('已经显示了')
return
}
console.log('显示 LoginForm')
this.state = 'show'
}
hide() {
if (this.state === 'hide') {
console.log('已经隐藏了')
return
}
console.log('隐藏 LoginForm')
this.state = 'hide'
}
private static instance: LoginForm | null = null
static getInstance(): LoginForm {
// 注意这里的 this
if (this.instance == null) this.instance = new LoginForm()
return this.instance
}
}
const loginForm1 = LoginForm.getInstance()
const loginForm2 = LoginForm.getInstance()
常见使用地方 自定义事件 eventBus 全局只有一个 Vuex Redux store 全局只有一个
let instance;
class DBConnection {
constructor(uri) {
if(instance) {
throw new Error('You can only create one single DB connection!');
}
this.uri = uri;
instance = this;
}
connect() {
console.log(`DB ${this.uri} has been connected!`);
}
disconnect() {
console.log('DB disconnected');
}
}
const connection = Object.freeze(new DBConnection('mongodb://...'));
export default connection;
from what we see the output is 4 is because we import file1 we also import singleton modules we didn't declare the actual singleton here but the actual output become 4