在 nest.js 中实施策略

时间:2021-04-22 17:05:15

标签: dependency-injection singleton nestjs strategy-pattern

我正在尝试为服务使用策略模式,但是我尝试用作策略上下文的模块似乎只坚持两者之一。下面是示例代码:

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”。可以让狗吠吗?

0 个答案:

没有答案