CSharp examples for Design Patterns:Observer Pattern
Implement the Observer Pattern
using System;/*w w w . j a v a 2 s. com*/ public class ValueChangedEventArgs : EventArgs { private readonly int oldValue, newValue; public ValueChangedEventArgs(int oldTemp, int newTemp) { oldValue = oldTemp; newValue = newTemp; } public int OldValue { get { return oldValue; } } public int NewValue { get { return newValue; } } } public delegate void ValueChangedEventHandler(Object sender, ValueChangedEventArgs args); public class ValueChangeObserver { public ValueChangeObserver(Thermostat t) { t.ValueChanged += this.ValueChange; } public void ValueChange(Object sender,ValueChangedEventArgs temp) { Console.WriteLine ("ChangeObserver: Old={0}, New={1}, Change={2}", temp.OldValue, temp.NewValue, temp.NewValue - temp.OldValue); } } public class ValueAverageObserver { private int sum = 0, count = 0; public ValueAverageObserver(Thermostat t) { t.ValueChanged += this.ValueChange; } public void ValueChange(Object sender, ValueChangedEventArgs temp) { count++; sum += temp.NewValue; Console.WriteLine ("AverageObserver: Average={0:F}", (double)sum / (double)count); } } public class Thermostat { private int temperature = 0; public event ValueChangedEventHandler ValueChanged; virtual protected void OnValueChanged(ValueChangedEventArgs args) { if (ValueChanged != null) { ValueChanged(this, args); } } public int Value { get { return temperature; } set { ValueChangedEventArgs args = new ValueChangedEventArgs(temperature, value); temperature = value; OnValueChanged(args); } } } class MainClass { public static void Main() { Thermostat t = new Thermostat(); new ValueChangeObserver(t); new ValueAverageObserver(t); do { Console.WriteLine(Environment.NewLine); Console.Write("Enter current temperature: "); try { t.Value = Int32.Parse(Console.ReadLine()); } catch (Exception) { Console.WriteLine("Terminating Observer Pattern Example."); return; } } while (true); } }