vendredi 10 avril 2020

How to dynamically instantiate array of classes based on their class type in Typescript

I implemented a strategy pattern as follow

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));
}

the caller may use the factory as follow:

new Factory().of(7) //-> returns an instance of Rule1

Question: Is there a way in typescript to create Factory.Rules dynamically based on the class type (IRule) ???

In c# this could be done as follow:

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();




Aucun commentaire:

Enregistrer un commentaire