Scenario: say I have a base class SketchbookEventObserver
and derived classes MouseClickObserver
, TouchObserver
and TextChangedObserver
.
All of these SketchbookEventObserver
s have to make a network request with data about the event that happened:
MouseClickObserver
- coordinates of the mouse click.
TouchObserver
- coordinates and duration of touch.
TextChangedObserver
- the old and new text with a text box identifier.
All of these observers are registered on a UIEventRegistry
class. When an event happens, it woud call OnEvent
on each observer, and pass as params:
- The type of event - mouse click / touch / text changed. This is represented by an ID.
- The data about the event - as described above. Each type of event will have different types of data.
However, I cannot override OnEvent
with different input parameters in each of the derived classes. If I have the input parameter generic and polymorphic, say EventData
with a GetData()
function, I would still need to override GetData()
in derived classes of EventData
, which will have different return values. This is also impossible.
The other option is to not have any inheritance between these observers, and treat them as separate entities. EventRegistry
will have an array / list of observers of each type, where their types are known, then call mMouseClickObservers[i].OnEvent()
for a mouse click event, mTouchObservers[i].OnEvent()
for a touch event, and so on.
But this means that EventRegistry
will need to have knowledge about the concrete classes, which need to be exposed publicly if EventRegistry
is part of a different library / package.
Is there a better way to design this?