using System;
public class ValueChangedEventArgs : EventArgs
{
public readonly int OldValue, NewValue;
public ValueChangedEventArgs(int oldTemp, int newTemp)
{
OldValue = oldTemp;
NewValue = newTemp;
}
}
public delegate void ValueChangedEventHandler(Object sender, ValueChangedEventArgs args);
public class ValueChangeObserver
{
public ValueChangeObserver(MyValue 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(MyValue 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 MyValue
{
private int myvalue = 0;
public event ValueChangedEventHandler ValueChanged;
virtual protected void OnValueChanged(ValueChangedEventArgs args)
{
if (ValueChanged != null)
{
ValueChanged(this, args);
}
}
public int Value
{
get { return myvalue; }
set
{
ValueChangedEventArgs args = new ValueChangedEventArgs(myvalue, value);
myvalue = value;
OnValueChanged(args);
}
}
}
public class MainClass
{
public static void Main()
{
MyValue t = new MyValue();
new ValueChangeObserver(t);
new ValueAverageObserver(t);
t.Value = 100;
t.Value = 99;
t.Value = 88;
t.Value = 77;
}
}
|