带有execute方法的Typescript singleton



如何创建一个将强制调用特定方法的单例实例甚至普通实例?

例如:

logger.instance().configure({ logs: true });

new logger();
logger.configure({ logs: true });

如果调用一个没有链接配置方法的记录器,它将抛出一个错误。

谢谢!

通常当我们想要创建单例时,我们需要隐藏构造函数。我们制作构造函数private。为什么?有必要避免类的许多实例。但下一个问题可能会浮现在人们的脑海中:;如何初始化变量&";。我们可以通过configure方法:

class MyLogger
{
logs: boolean
private static _instance: MyLogger;
private constructor()
{
}
public static get Instance()
{
return this._instance || (this._instance = new this());
}
public configure({logs}){
this.logs = logs
}
}
const mySingletonInstance = MyLogger.Instance;

你可以这样配置:

const mySingletonInstance = MyLogger.Instance.configure({logs: true});

最新更新