diff --git a/src/common/utils/sington.ts b/src/common/utils/sington.ts new file mode 100644 index 0000000..252f4b3 --- /dev/null +++ b/src/common/utils/sington.ts @@ -0,0 +1,24 @@ +/** 单例模式 装饰器 + * @param clz + * @returns + */ +export function singtonPattern any>(clz: T) { + // 添加判断,确保装饰器只能用于类 + if (typeof clz !== 'function') { + throw new Error('单例模式装饰器只能修饰在类上') + } + + let instance: InstanceType + 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 +}