You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
1.1 KiB
37 lines
1.1 KiB
// 抽象基类,使用泛型来正确推导子类类型
|
|
class BaseSingleton {
|
|
static _instance
|
|
|
|
constructor() {
|
|
if (this.constructor === BaseSingleton) {
|
|
throw new Error("禁止直接实例化 BaseOne 抽象类")
|
|
}
|
|
|
|
if (this.constructor._instance) {
|
|
throw new Error("构造函数私有化失败,禁止重复 new")
|
|
}
|
|
|
|
// this.constructor 是子类,所以这里设为 instance
|
|
this.constructor._instance = this
|
|
}
|
|
|
|
static getInstance() {
|
|
const clazz = this
|
|
if (!clazz._instance) {
|
|
const self = new this()
|
|
const handler = {
|
|
get: function (target, prop) {
|
|
const value = Reflect.get(target, prop)
|
|
if (typeof value === "function") {
|
|
return value.bind(target)
|
|
}
|
|
return Reflect.get(target, prop)
|
|
},
|
|
}
|
|
clazz._instance = new Proxy(self, handler)
|
|
}
|
|
return clazz._instance
|
|
}
|
|
}
|
|
|
|
export { BaseSingleton }
|
|
|