Advertisement
Caminhoneiro

Basic delegate "observers"

Jan 8th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 KB | None | 0 0
  1.  
  2.     public delegate void StartSimulation();
  3.     class EventManager
  4.     {
  5.         public static event StartSimulation startSimulationEvent;
  6.         public static event StartSimulation startSimulation2Event;
  7.         public static event StartSimulation startSimulation3Event;
  8.  
  9.         public static void OnStartSimulationEvent()
  10.         {
  11.             Console.WriteLine("Called start!!\n");
  12.             if (startSimulationEvent != null)
  13.                 startSimulationEvent();
  14.  
  15.         }
  16.  
  17.         public static void OnStartSimulation2Event()
  18.         {
  19.             Console.WriteLine("Called start2 on root\n");
  20.             if (startSimulation2Event != null)
  21.                 startSimulation2Event();
  22.         }
  23.  
  24.     }
  25.  
  26.     class VisitedClass
  27.     {
  28.         public void SubscribeEvent()
  29.         {
  30.             EventManager.startSimulationEvent += SayHello;
  31.             Console.WriteLine("Subscribed!\n");
  32.         }
  33.  
  34.         void SayHello()
  35.         {
  36.             Console.WriteLine("Hello I have been visited!\n");
  37.         }
  38.  
  39.         public void UnsubscribeEvent()
  40.         {
  41.             EventManager.startSimulationEvent -= SayHello;
  42.             Console.WriteLine("Unsubscribed!\n");
  43.         }
  44.     }
  45.  
  46.  
  47.     class Program  
  48.     {
  49.         static void Main(string[] args)
  50.         {
  51.  
  52.             VisitedClass visitedClass = new VisitedClass();
  53.             visitedClass.SubscribeEvent();
  54.  
  55.             EventManager.OnStartSimulationEvent();
  56.  
  57.             visitedClass.UnsubscribeEvent();
  58.  
  59.             EventManager.OnStartSimulationEvent();
  60.  
  61.             Console.Read();
  62.  
  63.         }
  64.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement