我正在尝试为服务使用策略模式,但是我尝试用作策略上下文的模块似乎只坚持两者之一。下面是示例代码:
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 都返回“meow”。可以让狗吠吗?