Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design Pattern - Event Handling [closed]

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:

  1. 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.

  2. 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!

like image 262
williamg Avatar asked Oct 21 '22 05:10

williamg


1 Answers

I would look at the Observer design pattern. If you combine this with an Event Aggregator, you should have everything that you need.

like image 80
David Osborne Avatar answered Oct 24 '22 18:10

David Osborne