Design Pattern Examples
Overview of object-oriented design patterns
Observer_Exercise.cs
Go to the documentation of this file.
1
5
6using System;
7
9{
30 internal class Observer_Exercise
31 {
35 // ! [Using Observer in C#]
36 public void Run()
37 {
38 Console.WriteLine();
39 Console.WriteLine("Observer Exercise");
40
42
43 // The number producer is passed to the observers so the observers
44 // can get the number to display. The observers only see the
45 // INumberProducer interface, to minimize knowledge about the
46 // Subject.
47 ObserverForDecimal observerDecimal = new ObserverForDecimal(numberProducer);
48 ObserverForHexaDecimal observerHexadecimal = new ObserverForHexaDecimal(numberProducer);
49 ObserverForBinary observerBinary = new ObserverForBinary(numberProducer);
50
51 // Tell the number producer about the observers who are notified
52 // whenever the value changes.
53 IEventNotifications eventNotifier = numberProducer as IEventNotifications;
54 eventNotifier.SubscribeToNumberChanged(observerDecimal);
55 eventNotifier.SubscribeToNumberChanged(observerHexadecimal);
56 eventNotifier.SubscribeToNumberChanged(observerBinary);
57
58 // Call the number producer's Update() method a number of times.
59 // The observers automatically print out the current value in
60 // different bases.
61 for (int index = 0; index < 10; ++index)
62 {
63 Console.WriteLine(" Update {0} on number producer. Results from observers:", index);
64 numberProducer.Update();
65 }
66
67 // When done, remove the observers from the number producer.
68 // It's always good to clean up after ourselves.
69 eventNotifier.UnsubscribeFromNumberChanged(observerDecimal);
70 eventNotifier.UnsubscribeFromNumberChanged(observerHexadecimal);
71 eventNotifier.UnsubscribeFromNumberChanged(observerBinary);
72
73 Console.WriteLine(" Done.");
74 }
75 // ! [Using Observer in C#]
76 }
77}
Example of using the Observer Pattern in C#.
void Run()
Executes the example for the Observer Pattern in C#.
Represents an observer that prints out the current number from the Subject in binary.
Represents an observer that prints out the current number from the Subject in decimal.
Represents an observer that prints out the current number from the Subject in hexadecimal.
Represents the Subject in this example, in this case, a class that contains a single number that is u...
void Update()
Update the number then notify all observers.
Represents a Subject that takes observers implementing the IObserverNumberChanged interface.
void SubscribeToNumberChanged(IObserverNumberChanged observer)
void UnsubscribeFromNumberChanged(IObserverNumberChanged observer)
The namespace containing all Design Pattern Examples implemented in C#.