static void Main(string[] args) { Publisher dailyNoise = new Publisher(); // Register a couple of subscribers. Subscriber joe = new Subscriber("Joe", "Ah, the paper's in my rose bush again!"); joe.Subscribe(dailyNoise); Subscriber moe = new Subscriber("Moe", "Dang! Soggy paper again!"); moe.Subscribe(dailyNoise); // Also subscribe from Main() itself. Console.WriteLine("Main() subscribes."); dailyNoise.NewEdition += DailyNoise_NewEdition; // Put out a new edition. dailyNoise.Publish(DateTime.Today, "Latest Celebrity Arrest!"); // Unsubscribe joe. joe.UnSubscribe(dailyNoise); // Put out another edition. dailyNoise.Publish(new DateTime(2008, 1, 22), "Perp Walks!"); // Unsubscribe moe. moe.UnSubscribe(dailyNoise); // Put out another edition. dailyNoise.Publish(new DateTime(4008, 1, 22), "Busted again?!?"); Console.WriteLine("Main() unsubscribes."); dailyNoise.NewEdition -= DailyNoise_NewEdition; // Wait for user to acknowledge results. Console.WriteLine("Press Enter to terminate..."); Console.Read(); }
// UnSubscribe - Call this method to remove this Subscriber from the list of // subscribers to the NewEdition event. public void UnSubscribe(Publisher p) { Console.WriteLine("{0} unsubscribes.", Name); // Note: instead of 'new EventHandler<NewEditionEventArgs>(this.NewEditionPublished)', // you can use this shorthand form: just give the method name. Compare to Subscribe(). // (You can even put a lambda expression here: see Chapter 16 on lambda expressions.) p.NewEdition -= this.NewEditionPublished; }
// Subscribe - Call this method to add this Subscriber to the list of // subscribers to the NewEdition event. public void Subscribe(Publisher p) { Console.WriteLine("{0} subscribes.", Name); p.NewEdition += new EventHandler(this.NewEditionPublished); }