【发布时间】:2020-05-07 05:34:22
【问题描述】:
我正在使用带有 Typescript 的 VueJS 构建一个项目。我觉得使用服务而不是像 Vuex 这样的任何状态管理库很舒服。但是在编写服务时,我必须总是在每个服务类中复制粘贴一些代码,以使其单例为:
class MyService {
private static Instance: MyService;
public static getInstance() {
if (!MyService.Instance) {
MyService.Instance = new MyService();
}
return MyService.Instance;
}
private constructor() {}
}
我在考虑装饰器,所以我的问题是我们真的可以摆脱上面的代码并使用装饰器吗,我尝试了一些失败的尝试:
function service<T>(): T {
const Instance: T | null = null;
return !Instance ? new T() : Instance;
}
@service<MyService>()
或
function service(constructor: Function) {
const Instance: MyService | null = null;
return !Instance ? new MyService() : Instance;
}
@service
但这些都行不通。我不确定装饰器是否会成功,其他方法可能在这里有效,但我不知道,有什么建议吗?
【问题讨论】:
-
我没有答案,但我喜欢这个问题!
标签: typescript decorator