抽象的观察者类
具体的观察者类
抽象的目标对象类
实体目标
public abstract class Observer
{
protected Subject aSubject;
public Subject ObservedSubject
{
get{return aSubject;}
set{aSubject = value;}
}
public Observer()
{
}
public abstract void Update();
}
{
protected Subject aSubject;
public Subject ObservedSubject
{
get{return aSubject;}
set{aSubject = value;}
}
public Observer()
{
}
public abstract void Update();
}
具体的观察者类
public class ConcreteObserver : Observer
{
private string strObserverName;
public ConcreteObserver(string name)
{
strObserverName = name;
}
public override void Update()
{
System.Console.WriteLine("In Observer {0} : DataFrom subject {1}" ,
strObserverName,this.ObservedSubject.ImportantSubjectData);
}
}
{
private string strObserverName;
public ConcreteObserver(string name)
{
strObserverName = name;
}
public override void Update()
{
System.Console.WriteLine("In Observer {0} : DataFrom subject {1}" ,
strObserverName,this.ObservedSubject.ImportantSubjectData);
}
}
抽象的目标对象类
public class Subject
{
// 由于不知道有多少个观察者,所以建立了观察者链表
private ArrayList aryObserver = new ArrayList();
private string strImportantSubjectData = "Initial";
public string ImportantSubjectData
{
get{return strImportantSubjectData;}
set{strImportantSubjectData = value;}
}
public Subject()
{
}
public void Attach(Observer aObserver)
{
aryObserver.Add(aObserver);
aObserver.ObservedSubject = this;
}
public void Detach(Observer o)
{
}
public void Notify()
{
// 在数据发生改变以后,通知每个观察者
foreach(Observer observ in aryObserver)
{
observ.Update();
}
}
}
{
// 由于不知道有多少个观察者,所以建立了观察者链表
private ArrayList aryObserver = new ArrayList();
private string strImportantSubjectData = "Initial";
public string ImportantSubjectData
{
get{return strImportantSubjectData;}
set{strImportantSubjectData = value;}
}
public Subject()
{
}
public void Attach(Observer aObserver)
{
aryObserver.Add(aObserver);
aObserver.ObservedSubject = this;
}
public void Detach(Observer o)
{
}
public void Notify()
{
// 在数据发生改变以后,通知每个观察者
foreach(Observer observ in aryObserver)
{
observ.Update();
}
}
}
实体目标
public class ConcreteSubject : Subject
{
public ConcreteSubject()
{
}
public void GetState()
{
}
public void SetState()
{
}
}
{
public ConcreteSubject()
{
}
public void GetState()
{
}
public void SetState()
{
}
}