观察者模式:定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生改变时,会通知所有观察者对象,使它们能够自动更新自己。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 观察者模式
{
abstract class Subject
{
private IList<Observer> observers = new List<Observer>();
public void Add(Observer observer)
{
observers.Add(observer);
}
public void Delete(Observer observer)
{
observers.Remove(observer);
}
public void Notify()
{
foreach(Observer o in observers)
{
o.Update();
}
}
}
class ConcreteSubject : Subject
{
private string subjectState;
public string SubjectState
{
get { return subjectState; }
set { subjectState = value; }
}
}
abstract class Observer
{
public abstract void Update();
}
class ConcreteObserver : Observer
{
private string name;
private string observerState;
private ConcreteSubject subject;
public ConcreteObserver(ConcreteSubject subject,string name)
{
this.subject = subject;
this.name = name;
}
public override void Update()
{
observerState = subject.SubjectState;
Console.WriteLine("观察者{0}的状态是{1}", name, observerState);
}
public ConcreteSubject Subject
{
get { return subject; }
set { subject = value; }
}
}
class Program
{
static void Main(string[] args)
{
ConcreteSubject s = new ConcreteSubject();
s.Add(new ConcreteObserver(s, "X"));
s.Add(new ConcreteObserver(s, "Y"));
s.Add(new ConcreteObserver(s, "Z"));
s.SubjectState = "ABC";
s.Notify();
Console.Read();
}