I have this working TS code, it's a deep inheritance tree, what I want is to combine configurations (simplified sample):
abstract class Basechart {
config = {};
constructor() {
this.addConf({ baseOpt: 'baseOpt' });
}
addConf(newConf = {}) {
this.config = { ...this.config, ...newConf }; // combining configs
}
}
class Serial extends Basechart {
constructor() {
super();
this.addConf({ serialOpt: 'serialOpt' });
}
}
class Bar extends Serial {
constructor() {
super();
this.addConf({ barOpt: 'barOpt' });
}
}
class Pyramid extends Bar {
constructor() {
super();
this.addConf({ pyramidOpt: 'pyramidOpt' });
}
}
var p = new Pyramid();
alert(JSON.stringify(p.config));
As espected it prints a combined config:
{"baseOpt":"baseOpt","serialOpt":"serialOpt","barOpt":"barOpt","pyramidOpt":"pyramidOpt"}
What I want is to encapsulate the repeated/common part of my code (constructors), because all subClasses are instantiated the same way (adding specific config), then it should be defined in only one place, it would be something like:
constructor() {
super();
this.addConf(this.mySpecificConfig());
}
I tried structuring code in different ways but I can't achieve it (get combined conf + DRY). Exist a way to accomplish it in Typescript? exist a design pattern in theoretical OOP?
Aucun commentaire:
Enregistrer un commentaire