.net framework事件设计准则
namespace CSDemos.Model
{
public delegate void PubEventHandler(object sender,PubEventArgs e);
public class Publisher
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public Publisher(string name) {
this._name = name;
}
public event PubEventHandler PubComputer;
public event PubEventHandler PubLife;
//可以让子类重写
protected virtual void OnPubComputer(PubEventArgs e){ //触发事件
if (PubComputer != null)
{
//以免订阅者事件处理时间过长,发生并发问题。
PubEventHandler pubComputerTmp = PubComputer;
pubComputerTmp(this, e);
}
}
protected virtual void OnPubLife(PubEventArgs e)
{ //触发事件
if (PubLife != null)
{
//以免订阅者事件处理时间过长,发生并发问题。
PubEventHandler pubLifeTmp = PubLife;
pubLifeTmp(this, e);
}
}
public void DoPubComputer(string magazineName,DateTime dtPubdate) {
PubEventArgs e = new PubEventArgs(magazineName, dtPubdate);
OnPubComputer(e);
}
public void DoPubLife(string magazineName, DateTime dtPubdate)
{
PubEventArgs e = new PubEventArgs(magazineName, dtPubdate);
OnPubLife(e);
}
}
}
订阅者Subscriber类:
namespace CSDemos.Model
{
class Subscriber
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public Subscriber(string name)
{
this._name = name;
}
public void Receive(object sender,PubEventArgs e)
{
MessageBox.Show(string.Format("{0}于{1}收到{2}",this.Name,e.PubDate.ToString(),e.Name));
}
}
}
EventArgs:
namespace CSDemos.Model
{
public class PubEventArgs:EventArgs
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private DateTime _pubDate;
public DateTime PubDate
{
get { return _pubDate; }
set { _pubDate = value; }
}
public PubEventArgs(string name, DateTime dt)
{
this._name = name;
this._pubDate = dt;
}
}
}
Client调用:
Publisher pub = new Publisher("新华出版社");
Subscriber subZs = new Subscriber("张三");
Subscriber subLs = new Subscriber("李四");
pub.PubComputer += subZs.Receive;
pub.PubComputer += subLs.Receive;
pub.PubLife += subZs.Receive;
pub.DoPubComputer("电脑杂志", DateTime.Now);
pub.DoPubLife("生活杂志", DateTime.Now);