-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPublisher.cs
More file actions
67 lines (55 loc) · 1.89 KB
/
Publisher.cs
File metadata and controls
67 lines (55 loc) · 1.89 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using GofPatterns.Behavioral.ObserverPattern.Exceptions;
namespace GofPatterns.Behavioral.ObserverPattern;
/// <summary>
/// Implementation of the Publisher (or Broadcaster) interface.
/// </summary>
/// <typeparam name="TInput"></typeparam>
public class Publisher<TInput> : IPublisher<TInput>
{
private readonly List<ISubscriber<TInput>> subscribers = new();
public void AddSubscriber(ISubscriber<TInput> subscriber)
{
subscribers.Add(subscriber);
}
public void RemoveSubscribers()
{
subscribers.Clear();
}
public void NotifySubscribers(TInput input)
{
subscribers.ForEach(x => x.Update(input));
}
}
/// <summary>
/// Implementation of the Publisher (or Broadcaster) interface.
/// </summary>
/// <typeparam name="TInput"></typeparam>
/// <typeparam name="TCategory"></typeparam>
public class Publisher<TInput, TCategory> : IPublisher<TInput, TCategory> where TCategory : notnull
{
private readonly Dictionary<TCategory, IPublisher<TInput>> publishers = new();
public void AddSubscriber(ISubscriber<TInput> subscriber, TCategory category)
{
IPublisher<TInput> publisher;
if (publishers.TryGetValue(category, out var outputPublisher))
publisher = outputPublisher;
else
publishers[category] = publisher = new Publisher<TInput>();
publisher.AddSubscriber(subscriber);
}
public void RemoveSubscribers(TCategory category)
{
VerifySubscription(category);
publishers.Remove(category);
}
public void NotifySubscribers(TInput input, TCategory category)
{
VerifySubscription(category);
publishers[category].NotifySubscribers(input);
}
private void VerifySubscription(TCategory type)
{
if (!publishers.ContainsKey(type))
throw new NoSubscriptionFoundException($"No subscription found for category: {type}");
}
}