Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * requirements:
- - implement a class structure for the "Event" pattern (aka "Observer")
- - one class defines events (it's the "Observable"), and other classes subscribe delegates to the events ("Observers" or "Subscribers")
- - observable class can "Raise" the events when it wants, and the subscribed delegates will be invoked
- - observable class has full control over the event - it can raise it, clear it, etc
- - other classes can only subscribe and unsubscribe delegates from the observable's event
- * implementation
- - Event is represented by class Event<T>, where T is the type of the argument that the observable passes to the delegates when it raises the event
- - observable class (HasEvent) has an Event<T> field which it can use to control and raise the event
- - observable class exposes the event field through property of type IEvent<T>, which only allows subscribing and unsubscribing
- */
- using System;
- using System.Collections.Generic;
- class Program
- {
- static void Main()
- {
- var myHasEvent = new HasEvent();
- Action<int> sub1 = i => Console.WriteLine(i);
- myHasEvent.MyEvent.AddSubscriber(sub1);
- myHasEvent.MyEvent.AddSubscriber(i => Console.WriteLine(new string('a', i)));
- myHasEvent.Poke();
- myHasEvent.Poke();
- myHasEvent.Poke();
- myHasEvent.MyEvent.RemoveSubscriber(sub1);
- myHasEvent.Poke();
- // myHasEvent.MyEvent.Clear(); // we can't do that!
- }
- class HasEvent
- {
- public HasEvent()
- {
- }
- int poked = 0;
- public void Poke()
- {
- poked += 1;
- myEvent.Raise(poked);
- }
- Event<int> myEvent = new Event<int>();
- public IEvent<int> MyEvent { get { return myEvent; } }
- }
- interface IEvent<T>
- {
- void AddSubscriber(Action<T> subscriber);
- void RemoveSubscriber(Action<T> subscriber);
- }
- class Event<T> : IEvent<T>
- {
- readonly List<Action<T>> subscribers = new List<Action<T>>();
- public void AddSubscriber(Action<T> subscriber)
- {
- subscribers.Add(subscriber);
- }
- public void RemoveSubscriber(Action<T> subscriber)
- {
- subscribers.Remove(subscriber);
- }
- public void Raise(T value)
- {
- foreach(var act in subscribers)
- act(value);
- }
- public void Clear()
- {
- subscribers.Clear();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment