mercredi 17 novembre 2021

correct inheritance in TS to avoid 'this' accessing value to early?

Please see the following sample code:

abstract class BasicSystem {
    constructor(private basic: any) {
        this.bacicCall();
        this.extraCall();
    }
    private bacicCall() {
        this.basic.doThings();
    }
    protected abstract extraCall(): void;
}
class ExtraSystem extends BasicSystem {
    constructor(basic: any, private extra1: any, private extra2: any) {
        super(basic);
    }
    protected extraCall() {
        if (this.extra1.isGood) this.extra1.runSomething();
        else if (this.extra2.isGood) this.extra2.runSomethingElse();
        // 'this.extra1/2' here are obviously not going to work
        //  My question is:
        //  How do I write the correct pattern?
    }
}

One obvious way to 'fix' it is to NOT call the abstract function this.extraCall() in the base class. I understand TS base class haven't got the child class's private values at this stage. Leave that to the child class to call the this.extraCall() function later after super(basic) would 'fix' the problem, but that defeats the purpose especially if my base class code has more abstract functions & logics to run.

What is the correct design pattern to make a call to the abstract function in the base class, so that base class can call these abstract functions without having to worry how the children classes implement them?

Aucun commentaire:

Enregistrer un commentaire