mercredi 21 février 2018

Structuring reusable code

I have a class that does something similar to:

class B{
    void x(){
        statement-block1;
        statement-block2;
        statement-block3;
        statement-block4;
    }

    void y(){
        statement-block5;
        statement-block6;
        statement-block7;
        statement-block8;
    }
}

I need to add a new class that does this:

class C{
    void x(){
        statement-block1;
        statement-block200;
        statement-block3;
        statement-block4;
    }

    void y(){
        statement-block5;
        statement-block6;
        statement-block700;
        statement-block8;
    }
}

I was considering combining the reusable logic this way:

class A{
    void x(){
        statement-block1;
        statement-block2;
        u();
        statement-block4;
    }

    void y(){
        statement-block5;
        statement-block6;
        v();
        statement-block8;
    }

    virtual void u(){
        default-message;
    }

    virtual void v(){
        default-message;
    }
}

class B : A{
    void u(){
        statement-block3;
    }

    void v(){
        statement-block7;
    }
}

class C : A{
    void u(){
        statement-block200;
    }

    void v(){
        statement-block700;
    }
}

Is there a better way to implement this, a different/better way of injecting sub-class-specific code, or is there a design pattern I can use? In the future, I might have to add more classes similar to B and C.

Thanks!

Aucun commentaire:

Enregistrer un commentaire