So I want some advice on what design pattern to use in this situation. I have this object that handles user input such as mouse movement, key presses, and other events. I have a bunch of other objects of various types that I want to be able to "subscribe" to certain events. So for example object A may want to listen for an "a" key press, while object B wants to listen for a "b" key press. Both events come from the one InputHandler object, which is abstract so that the events can be extended in the application. I'm wondering what the best way to handle this is.
Options considered:
Give each object an InputHandler object that is set to a specific instance at runtime. The obvious con here is that each object that receives events would have to have its InputHandler set at runtime, so I would have to keep track of each object that does so.
Create a base class EventHandler and EventHandlerFactory. The factory could have the InputHandler set at runtime, and then each class could get an instance of EventHandler that has listens for events from the InputHandler. I'm not really sure what's wrong with this choice, but it doesn't seem like the most elegant solution.
Any suggestions are greatly appreciated!
I would look at the Observer design pattern. If you combine this with an Event Aggregator, you should have everything that you need.
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