angular - 使用 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();
}
}
解决方案
我的两分钱 - 在这种情况下,您不能依赖 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);
推荐阅读
- java - Java中的线程问题:具有相同优先级的两个线程应该没有“顺序”对吗?
- c# - 我有一个包含 PDF 文件的共享点列表,我想使用 LINQ 通过其 ID 检索文件,如何使用 linq 来执行此操作?
- python - 通过迭代列表、字典和常量来创建字符串
- javascript - 如何检查 Typescript 条件类型中的类型是否未定义?
- r - 在 R 中自定义条形图的颜色
- javascript - 带有打字稿的递归类型
- c# - dropbox-sdk-dotnet:如何获取刷新令牌和更新访问令牌
- python - 需要用Python获取第一个图片链接
- lambda - OCAML 反向列表说明
- javascript - Drag'n'drop:当我单击元素时,元素不会停留在其原始位置