How to handle multiple event sources through a single handler

I am stuck in developing a clean design for my problem (below). I looked at the pub / sub or observer pattern, but my problem seems to be the opposite of these approaches if I just don't think correctly. Maybe the Mediator template will work, but still it seems to me that this does not seem to be correct. So, any help in what design is needed here, please let me know :)

My problem is that I need a handler that can handle events from multiple sources. I need a hotkey manager that can manage events from multiple locations. IE If a key is pressed, then some action must occur. Or, if the button is pressed on a microphone (another source), then the action should happen.

My current idea is to implement the manager as a singleton (not a huge fan of this ...), and classes will be registered in it. Classes would need to implement an interface that would guarantee a specific event to which the manager joined (when they were registered). I just don’t like it, because the class will have to raise this event, which is not a guarantee of the contract itself

+4
source share
1 answer

Your current idea sounds great, but I would make the following settings:

  • there is no need for a manager to be single

  • Sources of events should not be registered in the hotkey manager, some other class (builder) may be responsible for registering them with the help of the manager, this eliminates the dependence on sources in the manager.

eg.

public class HotKeyManager { public void RegisterKeySource(IKeySource source) { source.OnKeyPress += this.KeyPressHandler; } public void KeyPressHandler(object sender, KeyPressEventArgs args) { // ... } // ... } public interface IKeySource { event EventHandler<KeyPressEventArgs> OnKeyPress; // ... } 

Some other classes handle the initial registration:

 var hotKeyManager = new HotKeyManager(); var keySource = new MyKeySource(); // Implements IKeySource hotKeyManager.RegisterKeySource(keySource); 
+3
source

All Articles