【发布时间】:2021-07-16 22:41:25
【问题描述】:
我正在尝试对服务使用策略模式,但是我尝试用作策略上下文的模块似乎只坚持两者之一。下面是示例代码:
animal.module.ts
@Module({})
export class AnimalModule {
static register(strategy): DynamicModule {
return {
module: AnimalModule,
providers: [{ provide: 'STRATEGY', useValue: strategy }, AnimalService],
imports: [],
exports: [AnimalService]
};
}
}
animal.service.ts
@Injectable()
export class AnimalService {
constructor (@Inject('STRATEGY') private strategy) {
this.strategy = strategy
}
public makeSound() {
return this.strategy.makeSound()
}
}
cat.module.ts
@Module({
imports: [
AnimalModule.register(catStrategy),
],
controllers: [CatController],
providers: [CatService],
})
export class CatModule {}
cat.service.ts
@Injectable()
export class CatService {
constructor(
private readonly animalService: AnimalService,
) {}
public makeSound() {
return this.animalService.makeSound()
}
}
dog.module.ts
@Module({
imports: [
AnimalModule.register(dogStrategy),
],
controllers: [DogController],
providers: [DogService],
})
export class DogModule {}
dog.service.ts
@Injectable()
export class DogService {
constructor(
private readonly animalService: AnimalService,
) {}
public makeSound() {
return this.animalService.makeSound()
}
}
cat.strategy.ts
class CatStrategy {
public makeSound() {
return 'meow';
}
}
export const catStrategy = new CatStrategy();
复制问题的回购:https://github.com/kunukmak/nestjs-strategy-problem-example
为了澄清,在这种情况下 catService.makeSound 和 dogService.makeSound 都返回“喵”。可以让狗叫吗?
【问题讨论】:
标签: dependency-injection singleton nestjs strategy-pattern