private IContainer components;
public virtual ISubject Subject //ISubject接口的方法
{
set
{
m_subject = (IssueSubject)value;
.....
}
}
Pane/StaffPane用户控件引用了此IssueTreeView,它同样也是观察者(Observer)对象.
Pane/StaffPane.cs
namespace IssueVision
{
public class StaffPane : UserControl, IObserver
{
....
private IssueTreeView itvViews;
private IContainer components = null;
// IObserver.Subject
public ISubject Subject
{
set
{
itvViews.Subject = (IssueSubject)value;
}
}
在MainForm.cs中调用此用户控件代码如下:
private IssueSubject m_issueSubject = null;
.....
m_issueSubject = new IssueSubject(this.components); //调用IssueSubject的构造函数
paneStaff.Subject = m_issueSubject;
通过调用IssueSubject的构造函数,是此观察者(Observer)对象注册到了目标(Subject)对象中.(通过容器的Container.Add())
这样就完成了OBSERVER(观察者)模式的第一步,观察者(Observer)对象的注册.下面我们来看第二步,目标(Subject)对象如何通知观察者(Observer)对象
这就需要使用到委托和事件了.在回来看IssueSubject
IssueSubject.cs
public class IssueSubject : Component, ISubject
{
#region Delagate and Event Declarations
.......
public delegate void ConflictDataChangedEventHandler(object sender, EventArgs e);
public delegate void LookupDataChangedEventHandler(object sender, EventArgs e);
// ConflictDataChanged changes when a conflict is resolved, or new conflicts are
// detected.
public virtual event ConflictDataChangedEventHandler ConflictDataChanged;
// LookupDataChanged is raised when lookup data is downloaded from the server
public virtual event LookupDataChangedEventHandler LookupDataChanged;
......
在IssueSubject中申明委托和事件,观察者(Observer)对象登记这些事件,那么当IssueSubject改变后,激活一个事件,那么所有的观察者(Observer)对象都能得到这个改变的通知,从而激活相应的处理.
再看Controls/IssueTreeView.cs
namespace IssueVision
{
// The IssueTreeView user control implements the view selection ui for IssueVision
public class IssueTreeView : UserControl, IObserver
{
.....
private TreeView trvViews;
private IssueSubject m_subject = null;
private IContainer components;
public virtual ISubject Subject //ISubject接口的方法
{
set
{
m_subject = (IssueSubject)value;
//登记IssueSubject的事件,并交给相关方法处理事件
m_subject.LookupDataChanged += new IssueSubject.LookupDataChangedEventHandler(this.Subject_LookupDataChanged);
m_subject.ConflictDataChanged += new IssueSubject.ConflictDataChangedEventHandler(this.Subject_ConflictDataChanged);
}
}
最后,在IssueSubject中激活这些事件.
IssueSubject.cs
private void LoadIssueData()
{
.......
m_dataSet.DataSetName = "IssueSubject";
if (LookupDataChanged != null)
{
LookupDataChanged(this, EventArgs.Empty);
}
}
通过这么简单的几个步骤,就实现了OBSERVER(观察者)模式,.NET框架提供的委托和事件机制很大的简化了模式的实现.
CopyRight © YellowWee 2004. All Right Reserved.