staafl

C# event pattern

Oct 16th, 2013
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. /*
  2. * requirements:
  3. - implement a class structure for the "Event" pattern (aka "Observer")
  4. - one class defines events (it's the "Observable"), and other classes subscribe delegates to the events ("Observers" or "Subscribers")
  5. - observable class can "Raise" the events when it wants, and the subscribed delegates will be invoked
  6. - observable class has full control over the event - it can raise it, clear it, etc
  7. - other classes can only subscribe and unsubscribe delegates from the observable's event
  8. * implementation
  9. - 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
  10. - observable class (HasEvent) has an Event<T> field which it can use to control and raise the event
  11. - observable class exposes the event field through property of type IEvent<T>, which only allows subscribing and unsubscribing
  12. */
  13.  
  14. using System;
  15. using System.Collections.Generic;
  16.  
  17. class Program
  18. {
  19. static void Main()
  20. {
  21. var myHasEvent = new HasEvent();
  22. Action<int> sub1 = i => Console.WriteLine(i);
  23. myHasEvent.MyEvent.AddSubscriber(sub1);
  24. myHasEvent.MyEvent.AddSubscriber(i => Console.WriteLine(new string('a', i)));
  25. myHasEvent.Poke();
  26. myHasEvent.Poke();
  27. myHasEvent.Poke();
  28. myHasEvent.MyEvent.RemoveSubscriber(sub1);
  29. myHasEvent.Poke();
  30. // myHasEvent.MyEvent.Clear(); // we can't do that!
  31. }
  32.  
  33. class HasEvent
  34. {
  35. public HasEvent()
  36. {
  37. }
  38.  
  39. int poked = 0;
  40.  
  41. public void Poke()
  42. {
  43. poked += 1;
  44. myEvent.Raise(poked);
  45. }
  46.  
  47. Event<int> myEvent = new Event<int>();
  48. public IEvent<int> MyEvent { get { return myEvent; } }
  49. }
  50.  
  51. interface IEvent<T>
  52. {
  53. void AddSubscriber(Action<T> subscriber);
  54. void RemoveSubscriber(Action<T> subscriber);
  55. }
  56.  
  57. class Event<T> : IEvent<T>
  58. {
  59. readonly List<Action<T>> subscribers = new List<Action<T>>();
  60.  
  61. public void AddSubscriber(Action<T> subscriber)
  62. {
  63. subscribers.Add(subscriber);
  64. }
  65.  
  66. public void RemoveSubscriber(Action<T> subscriber)
  67. {
  68. subscribers.Remove(subscriber);
  69. }
  70.  
  71. public void Raise(T value)
  72. {
  73. foreach(var act in subscribers)
  74. act(value);
  75. }
  76.  
  77. public void Clear()
  78. {
  79. subscribers.Clear();
  80. }
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment