观察者模式 ---- C#

//保存所有的观察者对象的引用 并可以增加和删除观察者
abstract class HandleObserver
{
    public IList observers = new List();

    public void AddObserver(Observer observer)
    {
        observers.Add(observer);
    }

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

    public void Notify()
    {
        foreach (Observer o in observers)
        {
            o.Update();
        }
    }
}

//为具体的观察者定义一个接口 得到通知时更新
abstract class Observer
{
    public abstract void Update();
}

//将有关状态存入观察者对象
class ConcreteHadle : HandleObserver
{
    private string handleState;

    public string HandleState
    {
        get { return handleState; }
        set { handleState = value; }
    }
    
}

//实现更新接口
class ConcreteObserver : Observer
{
    private string observerState;
    private ConcreteHadle concreteHadle;

    public ConcreteObserver(ConcreteHadle concreteHadle)
    {
        this.concreteHadle = concreteHadle;
    }

    public override void Update()
    {
        observerState = concreteHadle.HandleState;
    }
}

调用:

ConcreteHadle ch = new ConcreteHadle();
ch.AddObserver(new ConcreteObserver(ch));

ch.HandleState = "ABC";
ch.Notify();

 

你可能感兴趣的:(C#)