Observer模式:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新。
第一个方法:使用传统方法(不用事件)
public interface Observer
{
void Update(Subject s);
}
public abstract class Subject
{
private ArrayList observers=new ArrayList();
protected string state="";
public virtual string State
{
get{return state;}
set{state=value;Notify();}
}
public void Add(Observer o)
{
observers.Add(o);
}
public void Remove(Observer o)
{
observers.Remove(o);
}
protected void Notify()
{
foreach(Observer o in observers)
{
o.Update(this);
}
}
}
public class ConcreteSubject:Subject
{
override public string State
{
get{return state + "继承";}
set{state=value+"_";Notify();}
}
}
public class FirstObserver:Observer
{
private string state="";
public void Update(Subject s)
{
state=s.State+"观察1";
}
public string State
{
get{return state;}
}
}
public class SecondObserver:Observer
{
private string state="";
public void Update(Subject s)
{
state=s.State+"观察2";
}
public string State
{
get{return state;}
}
}
第二个方法:使用C#事件机制
public delegate void MyEventHandler(Subject s);
public interface Observer
{
void Update(Subject s);
}
public abstract class Subject
{
protected string state="";
public event MyEventHandler Events=null;
public virtual string State
{
get{return state;}
set{state=value;Notify();}
}
public void Add(Observer o)
{
Events +=new MyEventHandler(o.Update);
}
public void Remove(Observer o)
{
Events -=new MyEventHandler(o.Update);
}
protected void Notify()
{
if(Events!=null)
{
Events(this);
}
}
}
public class ConcreteSubject:Subject
{
override public string State
{
get{return state + "继承";}
set{state=value+"_";base.Notify();}
}
}
public class FirstObserver:Observer
{
private string state="";
public void Update(Subject s)
{
state=s.State+"观察1";
}
public string State
{
get{return state;}
}
}
public class SecondObserver:Observer
{
private string state="";
public void Update(Subject s)
{
state=s.State+"观察2";
}
public string State
{
get{return state;}
}
}
下面是个测试类:
public class Test_Observer
{
private ConcreteSubject cs=null;
private FirstObserver fo=null;
private SecondObserver so=null;
public Test_Observer()
{
cs=new ConcreteSubject();
fo=new FirstObserver();
so=new SecondObserver();
cs.Add(fo);
cs.Add(so);
}
public void SetState(string str)
{
cs.State=str;
}
public string GetFirstObserverState()
{
return fo.State;
}
public string GetSecondObserverState()
{
return so.State;
}
}