单例模式 装饰器

This commit is contained in:
2025-10-18 20:10:32 +08:00
parent 7b12efd09c
commit 900a72e4c9

View 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
}