-
Notifications
You must be signed in to change notification settings - Fork 0
/
Commander.cs
50 lines (42 loc) · 1.37 KB
/
Commander.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace HumanRamen.Essentials
{
public interface ICommandHandler
{
void HandleCommand(string topic, string command);
}
public interface ICommander
{
void RegisterHandler(string topic, ICommandHandler handler);
void Command(string topic, string command);
}
public class Commander : ICommander
{
private readonly Dictionary<string, List<ICommandHandler>> _topicHandlers = new Dictionary<string, List<ICommandHandler>>();
public void RegisterHandler(string topic, ICommandHandler handler)
{
if (!_topicHandlers.ContainsKey(topic))
{
_topicHandlers.Add(topic, new List<ICommandHandler>());
}
_topicHandlers[topic].Add(handler);
}
public void Command(string topic, string command)
{
if (!_topicHandlers.ContainsKey(topic))
{
throw new ExceptionNoSuchTopic(topic);
}
Parallel.ForEach(_topicHandlers[topic],
handler => handler.HandleCommand(topic, command));
}
}
public class ExceptionNoSuchTopic : Exception
{
public ExceptionNoSuchTopic(string topic) : base(String.Format("No such topic {0}", topic))
{
}
}
}