-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObserver.cs
109 lines (93 loc) · 2.77 KB
/
Observer.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Observer
{
public class EventParams
{
static public EventParams Create(string key, object val)
{
var param = new EventParams();
param._map.Add(key, val);
return param;
}
public bool HasParam(string key)
{
return _map.ContainsKey(key);
}
public int GetInt(string key, int defVal)
{
if (_map.ContainsKey(key))
{
return (int)_map[key];
}
return defVal;
}
public void SetInt(string key, int val)
{
_map.Add(key, val);
}
public string GetString(string key, string defVal)
{
if (_map.ContainsKey(key))
{
return (string)_map[key];
}
return defVal;
}
public void SetString(string key, string val)
{
_map.Add(key, val);
}
Dictionary<string, object> _map = new Dictionary<string, object>();
}
public class Subject
{
public const string EVENT_BROADCAST = "Event.*";
Dictionary<string, List<ISubscriber>> _subscribers = new Dictionary<string, List<ISubscriber>>();
void Notify(string eventId, EventParams eventParams)
{
if (_subscribers.ContainsKey(eventId))
{
foreach (var subscriber in _subscribers[eventId])
{
subscriber.OnNotified(eventId, eventParams);
}
}
}
void Broadcast(string eventId, EventParams eventParams)
{
if (_subscribers.ContainsKey(EVENT_BROADCAST))
{
foreach (var subscriber in _subscribers[EVENT_BROADCAST])
{
subscriber.OnNotified(eventId, eventParams);
}
}
}
protected void NotifyAboutEvent(string eventId, EventParams eventParams)
{
Notify(eventId, eventParams);
Broadcast(eventId, eventParams);
}
public void Subscribe(string eventId, ISubscriber subscriber)
{
if (eventId == "" || eventId == "*")
{
eventId = EVENT_BROADCAST;
}
if (!_subscribers.ContainsKey(eventId))
{
_subscribers.Add(eventId, new List<ISubscriber>());
}
if (!_subscribers[eventId].Contains(subscriber))
{
_subscribers[eventId].Add(subscriber);
}
}
}
public interface ISubscriber
{
void OnNotified(string eventId, EventParams eventParams);
}
}