I read about observer pattern a while ago and absolutely loved it. Decoupling techniques are my passion. However, event/delegate-based systems seem much more convenient than lists of observers in pure version of pattern.
So now in my current project i'm reinventing (because there are already plenty of them) event system in which:
-
Observers know nothing about observables and vice versa.
-
Data handed to observers may or may not contain some information about the event.
-
Multiple event types are supported.
-
There aren't any static gods or singletons (any reason to make one?).
So far i've got:
// All event types.
public enum EventType { Type1, Type2, Type3 }
// Holder for data to pass here and there.
// I could use 'object' instead, but class seems more appropriate.
public class MyEventArgs : EventArgs {
public object data { get; }
public MyEventArgs(object data) {
this.data = data;
}
}
class EventManager {
private readonly Dictionary<EventType, Action<MyEventArgs>> events;
// Creating a dictionary with each type of event.
public EventManager() {
events = new Dictionary<EventType, Action<MyEventArgs>>();
foreach (var type in (EventType[])Enum.GetValues(typeof(EventType)))
events.Add(type, null);
}
public void Subscribe(EventType type, Action<MyEventArgs> action)
=> events[type] += action;
public void Unsubscribe(EventType type, Action<MyEventArgs> action)
=> events[type] -= action;
public void Trigger(EventType type, MyEventArgs args)
=> events[type].Invoke(args);
}
Now i don't have to introduce any additional fields (like events or delegates) inside observers and observables, i can use it like this:
manager.Trigger(EventType.Type1, new MyEventArgs(15));
And:
manager.Subscribe(EventType.Type1, SomeMethod);
Or:
manager.Subscribe(EventType.Type1, (args)=>{...});
This post may seem like some kind of tutorial, but i'm actually asking if there are some critical disadvantages in introduced system i don't see. I'd appreciate if you criticize my solution performance-wise, style-wise, architecture-wise or in any other way.
Aucun commentaire:
Enregistrer un commentaire