Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1.     interface INotifyable
  2.     {
  3.         void Notify();
  4.     }
  5.  
  6.     class Observed
  7.     {
  8.         public delegate void MyCoolDelegate();
  9.         public event MyCoolDelegate SomethingHappened;
  10.  
  11.         List<INotifyable> _mySubscribers = new List<INotifyable>();
  12.  
  13.         public void DoSomethingCool()
  14.         {
  15.             foreach (var subscriber in _mySubscribers)
  16.             {
  17.                 subscriber.Notify();
  18.             }
  19.  
  20.             if (SomethingHappened != null)
  21.                 SomethingHappened();
  22.         }
  23.  
  24.         public void SubscribeToMe(INotifyable subscriber)
  25.         {
  26.             _mySubscribers.Add(subscriber);
  27.         }
  28.     }
  29.  
  30.     class Observer1 : INotifyable
  31.     {
  32.         public Observer1(Observed observed)
  33.         {
  34.             observed.SomethingHappened += observed_SomethingHappened;
  35.             observed.SubscribeToMe(this);
  36.         }
  37.  
  38.         void observed_SomethingHappened()
  39.         {
  40.             Console.WriteLine("ZOMZ: I just saw something cool 1!");
  41.         }
  42.  
  43.         public void Notify()
  44.         {
  45.             Console.WriteLine("ZOMZ: I just saw something cool 2!");
  46.         }
  47.     }
  48.  
  49.     class Observer2 : INotifyable
  50.     {
  51.         public Observer2(Observed observed)
  52.         {
  53.             observed.SomethingHappened += observed_SomethingHappened;
  54.             observed.SubscribeToMe(this);
  55.         }
  56.  
  57.         void observed_SomethingHappened()
  58.         {
  59.             Console.WriteLine("OMFG: I just saw something cool 1!");
  60.         }
  61.  
  62.         public void Notify()
  63.         {
  64.             Console.WriteLine("OMFG: I just saw something cool 2!");
  65.         }
  66.     }
  67.  
  68.     class Program
  69.     {
  70.         static void Main(string[] args)
  71.         {
  72.             Observed o = new Observed();
  73.             Observer1 o1 = new Observer1(o);
  74.             Observer2 o2 = new Observer2(o);
  75.  
  76.             o.DoSomethingCool();
  77.  
  78.             Console.Read();
  79.         }
  80.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement