设计模式——观察者模式
作者:互联网
设计模式——观察者模式
观察者模式 定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,这个主题对象在状态发生变化时,会通知所有观察者对象,使他们能够自动更新自己
///看股票的同事
class StockObserver
{
private string name;
private Subject sub;
public StockObserver(string name, Subject sub)
{
this.name = name;
this.sub = sub;
}
//关闭股票行情
public void CloseStockMarket()
{
Console.WriteLine("{0} {1} 关闭股票行情,继续工作!",sub.SubjectState,name);
}
}
//看NBA 的同事
class NBAObserver
{
private string name;
private Subject sub;
public NBAObserver(string name, Subject sub)
{
this.name = name;
this.sub = sub;
}
//关闭股票行情
public void CloseNBADirectSeeding()
{
Console.WriteLine("{0} {1} 关NBA直播,继续工作!", sub.SubjectState, name);
}
}
//通知者接口
interface Subject
{
void Notify();
string SubjectState
{
get;
set;
}
}
delegate void EventHandler();
//老板类
class Boss : Subject
{
//声明一事件Update,类型为委托EventHandler
public event EventHandler Update;
private string action;
public string SubjectState { get { return action; } set { action = value; } }
public void Notify()
{
Update();//在访问“通知”方法时,调用“更新”
}
}
//前台秘书类
class Secretary:Subject
{
//声明一事件Update,类型为委托EventHandler
public event EventHandler Update;
private string action;
public string SubjectState { get { return action; } set { action = value; } }
public void Notify()
{
Update();//在访问“通知”方法时,调用“更新”
}
}
static void Main(string[] args)
{
//老板胡汉三
Boss huhansan = new Boss();
//看股票的同事
StockObserver tongshi1 = new StockObserver("魏关在", huhansan);
//看NBA的同事
NBAObserver tongshi2 = new NBAObserver("易管查", huhansan);
huhansan.Update += new 观察者模式.EventHandler(tongshi1.CloseStockMarket);
huhansan.Update += new 观察者模式.EventHandler(tongshi2.CloseNBADirectSeeding);
//老板回来
huhansan.SubjectState = "我胡汉三回来了";
//发出通知
huhansan.Notify();
}
标签:EventHandler,sub,string,观察者,模式,Update,设计模式,public,name 来源: https://blog.csdn.net/weixin_43945471/article/details/111383613