有几个疑问

来源:12-7 【仿 Nestjs 装饰器实战】 依赖注入实现引发的深度思考+代码持续优化-2

Bless_Me_Plz

2023-08-07

① 关于singleton decorator

Reflect.defineMetadata("singleton", isSingleton, targetClassPrototype, propertyKey);

这行代码只是把 true / false 存在了singleton这个元数据key里,我感觉这个boolean值意义不大?
由于下面代码保存了ServiceImplInstanceOrClass为class本身或者instance,我认为只需要判断 ServiceImplInstanceOrClass 是不是 instanceof Reflect.getMetadata("design:type", targetClassPrototype, propertyKey)就能确定是singleton还是non-singleton了.

Reflect.defineMetadata("ServiceImplInstanceOrClass",
      ServiceImplInstanceOrClass, targetClassPrototype, propertyKey)

② 关于 autowired Decorator

if (metaSingleton) {//如果是单件模式
  console.log("我是Autowired装饰器,单件模式获取对象");
  ServiceImplInstance = ServiceImplInstanceOrClass
} else {
  ServiceImplInstance = new ServiceImplInstanceOrClass();
}

这段代码岂不是使得 autowired decorator 和 singleton decorator绑定了?
想使 autowired 就必须先至少用一次singleton?
是不是应该check一下ServiceImplInstanceOrClass是否为空,如果为空,默认用targetClassPrototype来new一个instance出来?
这里还呼应我的上面的第一个①问题,是不是不用check metaSingleton,直接check ServiceImplInstanceOrClass?如果为空,默认用Reflect.getMetadata("design:type", targetClassPrototype, propertyKey),如果不为空,判断是否是 Reflect.getMetadata("design:type", targetClassPrototype, propertyKey) 的instance: 如果true,表明是单例直接用。如果false,表明不是单例,直接 new ServiceImplInstanceOrClass()

总之,我感觉AutowiredSingleton有点耦合了,不知道上面的问题是不是合理?

写回答

1回答

keviny79

2023-08-07

(1)关于singleton decorator  ,你说的 ” 下面代码保存了ServiceImplInstanceOrClass为class本身或者instance“  的前提是在 if 单例模式判断的前提下得到的,  if 单例模式判断是因 ,才导致ServiceImplInstanceOrClass是个实例还是个类和 在单例模式的判断下第一次进来实例化,第二次进来什么都不做直接返回,所以在没确定 ServiceImplInstanceOrClass的具体是个啥之前,去用 ServiceImplInstanceOrClass  instanceof Reflect.getMetadata("design:type", targetClassPrototype, propertyKey) 和 xx instacneof 。。。。 没区别了。

(2) 关于正确理解耦合:耦合的不好主要表现在当一个类被多个类或方法等被很多位置用到了,那我们就要想办法降低耦,比如一个工具类的文件,字符操作方法的提取,但这里的装饰器只写了一次,就不用考虑耦合问题了,并且如果你不用单例模式判断,用其他方法来实现,代码写起来可能要更麻烦。


0
0

TypeScript 从入门到深度掌握,晋级TS高手

200+技术点,22 场景应用,Vue3 源码 TS 用法剖析

430 学习 · 53 问题

查看课程