行为模式之观察者模式 笔记

资料来源:吕震宇老师的博客

观察者模式():如果一些对象变化了,那么与他紧密相连的一些对象也要实现相应的变化

图例:

 

  行为模式之观察者模式 笔记_第1张图片

 

 

示例性代码:

 

// Observer pattern -- Structural example  
using System;
using System.Collections;

// "Subject"
abstract class Subject
{
  // Fields
  private ArrayList observers = new ArrayList();//估摸这个ArrayList数组可以随时转换成任何类型的数组 

  // Methods
  public void Attach( Observer observer )
  {
    observers.Add( observer );
  }

  public void Detach( Observer observer )
  {
    observers.Remove( observer );
  }

  public void Notify()
  {
    foreach( Observer o in observers )//这个抽象函数的方法被子类调用了,所以就有了引用Observer抽象类的感觉 
      o.Update();
  }
}

// "ConcreteSubject"
class ConcreteSubject : Subject
{
  // Fields
  private string subjectState;

  // Properties
  public string SubjectState//具体被观察者对象子类更新自己的状态 
  {
    get{ return subjectState; }
    set{ subjectState = value; }
  }
}

// "Observer"
abstract class Observer
{
  // Methods
  abstract public void Update();
}

// "ConcreteObserver"
class ConcreteObserver : Observer
{
  // Fields
  private string name;
  private string observerState;
  private ConcreteSubject subject;//每个具体观察者是VIP会员,所以可以拥有一个具体的被观察者对象 

  // Constructors
  public ConcreteObserver( ConcreteSubject subject,  
    string name )
  {
    this.subject = subject;
    this.name = name;
  }

  // Methods
  override public void Update()
  {
    observerState = subject.SubjectState;
    Console.WriteLine( "Observer {0}'s new state is {1}",
      name, observerState );
  }

  // Properties
  public ConcreteSubject Subject
  {
    get { return subject; }
    set { subject = value; }
  }
}

/// <summary>
/// Client test
/// </summary>
public class Client
{
  public static void Main( string[] args )
  {
    // Configure Observer structure
    ConcreteSubject s = new ConcreteSubject();
    s.Attach( new ConcreteObserver( s, "1" ) );
    s.Attach( new ConcreteObserver( s, "2" ) );
    s.Attach( new ConcreteObserver( s, "3" ) );

    // Change subject and notify observers
    s.SubjectState = "ABC";
    s.Notify();
  }
}


 

你可能感兴趣的:(行为模式之观察者模式 笔记)