Observer Design Pattern : Observer Pattern « Design Patterns « C# / CSharp Tutorial






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;        
    }
}
ChangeObserver: Old=0, New=100, Change=100
AverageObserver: Average=100.00
ChangeObserver: Old=100, New=99, Change=-1
AverageObserver: Average=99.50
ChangeObserver: Old=99, New=88, Change=-11
AverageObserver: Average=95.67
ChangeObserver: Old=88, New=77, Change=-11
AverageObserver: Average=91.00








28.3.Observer Pattern
28.3.1.Observer Design Pattern