首页 > 解决方案 > 使用 Angular 和 Typescript 的策略模式

问题描述

我想在 Angular/Typescript 中实现策略模式并在组件中使用服务;服务将策略接口作为构造函数参数。此外,约束是服务依赖于角度级别的其他一些注入服务。

我正在研究文档,但找不到解决方法。我不想以过度设计的代码结束,寻找简单的解决方案来实现策略模式。

请参阅下面的模拟代码:

export interface IStrategy {
    calculate(a,b): number;
}

export class MinusStrategy implements IStrategy {
    calculate(a,b): number {
        return a - b;
    }
}

export class PlusStrategy implements IStrategy {
    calculate(a,b): number {
        return a + b;
    }
}

@Injectable() 
export class CalculatorService {
    // I understand it is not possible to have DI of the Interface here for calcStrategy 
    constructor(private http: HttpClient; private calcStrategy: IStrategy);
    
    getByCalc() {
        this.http.get('someurl?calc=' + calcStrategy.calculate(1,1));
    }
}

@Component(// skipped config here...)
export class MyComponent implements OnInit {
    // How to inject appropriate concrete strategy (and either autowire or provide httpClient?)
    constructor(private service: new CalculatorService(httpClient, new MinusStrategy()));
    
    useInComponent() {
        this.service.getByCalc();
    }
}

标签: angulartypescriptdesign-patterns

解决方案


我的两分钱 - 在这种情况下,您不能依赖 DI 提供具体实例。DI 无法知道每个上下文中需要哪种类型的实例。

我建议在这里使用工厂模式。例如 -

@Injectable()
export class StrategyFactory {
  createStrategy<T extends IStrategy>(c: new () => T): T {
    return new c();
  }
} 

//then you can inject StrategyFactory in your service class, use it like -
factory.createStrategy(MinusStrategy).calculate(2, 1); 

推荐阅读