From 900a72e4c95f00af8654a6c425a152f3455b8db3 Mon Sep 17 00:00:00 2001 From: Azure <983547216@qq.com> Date: Sat, 18 Oct 2025 20:10:32 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8D=95=E4=BE=8B=E6=A8=A1=E5=BC=8F=20?= =?UTF-8?q?=E8=A3=85=E9=A5=B0=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/common/utils/sington.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/common/utils/sington.ts 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 +}