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






using System;
  public delegate void ChangedEventHandler(object sender, EventArgs e);

  public class Subject
  {
    private string data;
    public event ChangedEventHandler Changed;

    public string InterestingData
    {
      get{return data;}
      set{
        data = value;
        this.OnChanged(EventArgs.Empty);
      }
    }
    protected virtual void OnChanged (EventArgs e)
    {
      if (Changed !=null)
        this.Changed(this,e);
    }
    public Subject(){;}
  }

  public class Observer
  {
    private Subject data;
    private string observerName;

    public Subject ObservedObject
    {
      get {return data;}
      set {data = value;}
    }

    private void DataChanged (object sender, EventArgs e)
    {
      Console.WriteLine(observerName);
      Console.WriteLine(data.InterestingData);
    }
    public void Attach()
    {
      data.Changed += new ChangedEventHandler(DataChanged);
    }
    public void Detach()
    {
      data.Changed -= new ChangedEventHandler(DataChanged);
    }
    public Observer (string name)
    {
      observerName = name;
    }
  }
  class Client{
    static void Main(string[] args){
      Subject observedAssemblyLine = new Subject();
      Observer observerA = new Observer("A Observer");
      Observer observerB = new Observer("B Observer");
      
      observerA.ObservedObject = observedAssemblyLine;
      observerB.ObservedObject = observedAssemblyLine;

      observerA.Attach();
      observerB.Attach();
      observedAssemblyLine.InterestingData = "# 001 is now finished!";
      observerA.Detach();
      observedAssemblyLine.InterestingData = "# 002 is now finished!";

    }
  }








28.7.Observer Pattern
28.7.1.Observer Patterns