单例模式 装饰器
This commit is contained in:
24
src/common/utils/sington.ts
Normal file
24
src/common/utils/sington.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
/** 单例模式 装饰器
|
||||||
|
* @param clz
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export function singtonPattern<T extends new (...args: any[]) => any>(clz: T) {
|
||||||
|
// 添加判断,确保装饰器只能用于类
|
||||||
|
if (typeof clz !== 'function') {
|
||||||
|
throw new Error('单例模式装饰器只能修饰在类上')
|
||||||
|
}
|
||||||
|
|
||||||
|
let instance: InstanceType<T>
|
||||||
|
const proxy = new Proxy(clz, {
|
||||||
|
construct(target, args, newTarget) {
|
||||||
|
if (!instance) {
|
||||||
|
instance = Reflect.construct(target, args, newTarget)
|
||||||
|
}
|
||||||
|
return instance
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
proxy.prototype.constructor = proxy
|
||||||
|
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user