Я реализовал шаблон стратегии следующим образом
interface IRule {
isMatch(in: number): boolean;
}
class Rule1: IRule {
isMatch(in: number) {
return number === 7;
}
}
class Rule2: IRule {
isMatch(in: number) {
return number % 2 === 0;
}
}
class Factory {
const rules: IRule[] = [];
constructor() {
//problem is here
this.rules = [new Rule1(), new Rule2()];
}
public of(in: number) {
return this.rules.find(r => r.isMatch(in));
}
}
Вызывающий абонент может использовать фабрику следующим образом:
new Factory().of(7) //-> returns an instance of Rule1
Вопрос:
Есть ли в TypeScript способ динамического создания Factory.Rules
на основе типа класса IRule
?
В C# это можно сделать следующим образом:
var ruleTypeInterface = typeof(IRule);
var rulesType = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => ruleTypeInterface.IsAssignableFrom(t) && t.IsClass);
this.rules = rulesType.Select(rt => Activator.CreateInstance(rt) as IRule).ToArray();