lundi 5 juillet 2021

Preferring composition over inheritance in the diamond problem

Suppose we have 3 classes Button, Clickable and Rectangle.
Neither of them are abstract and can exist on their own. All of them have a position member variable. When the Button class inherits from Clickable and Rectangle they should share a common position variable.
My implementation:

struct Positionable {
    struct Position {
        int x, y;
    } position;
};
struct Rectangle: virtual public Positionable {
    // ...
};
struct Clickable : virtual public Positionable {
    // ...
};
struct Button : virtual public Positionable, public Rectangle, public Clickable {
    Button() {
        this->position.x = 1;
        assert(Rectangle::position.x == 1);
        assert(Clickable::position.x == 1);
        assert(Positionable::position.x == 1);
    }
} test;

The problem with this (besides the 3 forms of the word position) is that I feel, that I'm breaking the composition over inheritance principle, because I inherit only to include a variable.
Is there a design pattern with the same behavior? How can I use composition in this situation?

Aucun commentaire:

Enregistrer un commentaire