一个来自单例的装饰器的骚操作

跳过类控制,直接控制变量,实现单例自由
function singleton(target: any, propertyKey: string) {
const privateKey = _${propertyKey};

Object.defineProperty(target, propertyKey, {
    get: function () {
        if (!this[privateKey]) {
            this[privateKey] = new this();
        }
        return this[privateKey];
    },
    configurable: false,
    enumerable: false,
});

}

export class ClassTest {
@singleton
public static instance: ClassTest;

public test() {
    cc.log('ClassTest');
}

}

请问一下怎么用呢? 这样吗ClassTest.instance

是的,执行 ClassTest.instance.test()
输出 “ClassTest”

那为啥不直接public static instance: ClassTest = new ClassTest(); 况且这也不能叫单例吧 顶多算是单例型使用方式

别呀 直接干沉默了 感谢楼主分享

public static instance: ClassTest = new ClassTest() 这个写法 外部是可以赋值更改的

又到了我最喜欢的茴字有几种写法环节

// case A

export class A {

    static readonly ins = new A();

    testA() { }

}

A.ins.testA();

// case B

class B {

    testB() { }

}

export const b = new B();

b.testB();

// case C

const insMap = new WeakMap();

function Ins<T>(clazz: new (...args: any[]) => T): T {

    if (!insMap.has(clazz)) {

        insMap.set(clazz, new clazz());

    }

    return insMap.get(clazz);

}

class C {

    testC() { }

}

Ins(C).testC();

我在ts中写单例悖论:如果我知道一个类要用单例,我为何不直接导出一个常量?

哈哈,主要是想偷懒,仅此而已

对头,我那个是无法外部赋值的,只能读取

我之前看一个项目,单利导出都是 一个小游记至少一个单利,有些地方还是继承性的 后来我改了个

//对继承无影响
export function SingleFunc(target: any) {
       target.Ins = function (thisMe: any, ...args) {
           if (!target.__ins__) {
               target.__ins__ = new target(...args)
           }
           return target.__ins__
       }
       return target
   }

   declare global {
       interface Function {
           Ins<T>(arg: { new(...args): T }, ...params: any[]): T
     }
  }

example:
 @SingleFunc
  class A {
  }
  let a = A.Ins(A)

首先这个privateKey并不是私有的 你可以把_改成# 然后类构造函数前面也要加上private

这样会给所有的Function加上Ins,算是污染吧

大家无非就是想优雅一点 但好像也没那么优雅 我也赞同为何不直接一个new实例导出

mark :rofl: :rofl: :rofl:欢乐

对 一般会命名一个不一样的名字

我是两者都用

优雅永不过时 :rofl: 使用装饰器或者继承单例类都是一种优雅

还有更繁琐的,但是我个人觉得这样做很low
import { Node } from ‘cc’;

export interface SingletonBase {
init(target: Node): void;

reset(): void;

}

export function Singleton() {
return class Singleton implements SingletonBase {
public init(target: Node) {}
public reset(): void {}

    private static _instance: T;

    public static get Instance(): T {
        if (!this._instance) {
            this._instance = new this() as T;
        }
        return this._instance;
    }
};

}

@ccclass(‘EventManager’)
export class EventManager extends Singleton() {}

我就是这么写的 :joy: