我正在使用 VueJS 和 Typescript 构建一个项目。我觉得使用服务而不是像 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>()
or
function service(constructor: Function) {
const Instance: MyService | null = null;
return !Instance ? new MyService() : Instance;
}
@service
但这些都是行不通的。我不确定装饰器是否能做到这一点,其他方法可能在这里工作,但我没有任何想法,有什么建议吗?
也许你可以尝试如下
singletone.decorator.ts
const serviceList: any[] = [];
export function AsSingletone() {
return (target: any): void => {
if(target.prototype.Instance) {
return;
}
serviceList.push(target);
Object.defineProperty(target, 'Instance', {
get: function () {
if (target.prototype.Instance) {
return target.prototype.Instance;
}
const instance = new target();
target.prototype.Instance = instance;
Object.defineProperty(target, 'Instance',
{ get: function () { return instance; } }
);
return instance;
}, configurable: true
});
};
}
export function registeredServiceList(): any[] {
return serviceList;
}
服务.ts
import { AsSingletone } from "./singletone.decorator";
@AsSingletone()
export class MyService {
public static readonly Instance: MyService;
}
获得访问权限
console.log(MyService.Instance);
设置抛出异常
MyService.Instance = (new MyService() as any).Instance as MyService;
VS 代码片段模板,开始输入 - single
"Singletone": {
"prefix": ["singl"],
"body": [
"AsSingletone()\r",
"export class ${0}Service {\r",
"\tpublic static readonly Instance: ${0}Service;",
"}"],
"description": "Singletone service template"
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)