Justin Pihony
Justin Pihony

Reputation: 67075

How to handle multiple event sources via one handler

I am stuck on coming up with a clean design for my problem (below). I have contemplated a pub/sub or observer pattern, but my problem seems opposite of these approaches unless I am just not thinking correctly. Maybe the Mediator pattern will work, but it still doesnt quite seem right to me for some reason. 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 places. IE. If a keypress is encountered, then some action should happen. Or, if a button is pressed on a microphone (different source), then an action should happen.

My current idea is to implement the manager as a singleton (not a huge fan of this...), and have classes register in the manager. The classes would need to implement an interface that would guarantee a certain event that the manager would attach to (when they were registered). I just don't like this because the class would need to raise this event, which is not something that is guaranteed by the contract per se

Upvotes: 4

Views: 1164

Answers (1)

Ergwun
Ergwun

Reputation: 12978

Your current idea sounds fine, but I would make the following tweaks:

  • no need for the manager to be a singleton;

  • the event sources do not need to register themselves with the hotkey manager, some other class (a builder) could be responsible for registering them with the manager, this removes the dependency from the sources on the manager.

E.g.

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 class handles the source registration:

var hotKeyManager = new HotKeyManager();

var keySource = new MyKeySource(); // Implements IKeySource

hotKeyManager.RegisterKeySource(keySource);

Upvotes: 3

Related Questions