mercredi 20 janvier 2021

How to design the code? Double reference problem

I'm developing a GUI library in C++. I have a class named Sidebar that draws the sidebar. Also, I have an interface SidebarElement that provides an interface to draw something sidebar element. I have a class SidebarTab that implements the SidebarElement interface, this class draws a clickable button. When the button is pressed sidebar element have to somehow notify the Sidebar class about changing the tab. I can pass the Sidebar instance to SidebarElement and call the Sidebar's method notify from SidebarElement, but it is the double reference problem. As far as I know, it's a bad practice. Example code: SidebarElement interface:

class SidebarElement {
public:
    virtual ~SidebarElement() {}

    virtual void SetSidebar(Sidebar* sidebar) = 0;

    virtual void Draw(const SidebarElementDrawParams& params) = 0;

    virtual float GetHeight() = 0;
};

Sidebar class:

class Sidebar {
public:
    void AddElement(SidebarElement* element);
    
    void Draw();
    
    // Method for call from SidebarElement derivatives
    void NotifyChangeTab(int tab_id);
};

Aucun commentaire:

Enregistrer un commentaire