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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With