Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for inheriting from multiple classes?

So I'm working on a GUI library and I have 3 classes: UIElement, the base for every UI object, UIContainer, which implements the possibility to hold other child-elements and UIRect which implements position and size for elements. Now I would like to create a class that uses both UIRect and UIContainer. Obviously this is impossible this way, but is there any elegant solution for this problem?

like image 665
pixartist Avatar asked May 15 '26 20:05

pixartist


1 Answers

Here is one possibility: inherit from one of the classes (say, UIRect), and embed the other (say, UIContainer). Implement the interface of IUIContainer bu forwarding all calls to the embedded object.

class UIRect {
    ...
}
interface IUIContainer {
    IEnumerable<IUIElement> AllElements {get;}
    void AddElement(IUIElement toAdd);
}
class UIContainer : IUIContainer {
    public IEnumerable<IUIElement> AllElements {
        get {
            ...
        }
    }
    public void AddElement(IUIElement toAdd) {
        ...
    }
}
class Multiple : UIRect, IUIContainer {
    private readonly IUIContainer _cont = new UIContainer();
    ...
    public IEnumerable<IUIElement> AllElements {
        get {
            return _cont.AllElements;
        }
    }
    public void AddElement(IUIElement toAdd) {
        _cont.AddElement(toAdd);
    }
}

Another possibility is to use two interfaces, and share implementation through extension methods.

like image 196
Sergey Kalinichenko Avatar answered May 17 '26 10:05

Sergey Kalinichenko