验证中...
私信发送成功
语言: C#
分类: 游戏开发
最后更新于 2017-09-28 21:55
Obsever.cs
原始数据 复制代码
//观察者模式
interface ISubject //抽象发布者
{
void Notify();
string Subject { get; set; }
}
//事件委托处理
delegate void PatrolHandler();
class Teacher : ISubject
{
//事件不可以当做形参传递,但是委托可以
public event PatrolHandler Update;
public string Subject { get; set; }
public void Notify()
{
if (Update!=null)
{
Update();
}
}
}
//订阅者
class PlayObServer
{
private string name;
private ISubject sub;//定义一个抽象发布者的引用
public PlayObServer(string name,ISubject sub)
{
this.name = name;
this.sub = sub;
}
//放下手机,假装写代码
public void PlayPhone()
{
Console.WriteLine("{0} {1}放下手机,假装写代码",sub.Subject,name);
}
}
class ViewObServer
{
private string name;
private ISubject sub;//定义一个抽象发布者的引用
public ViewObServer(string name, ISubject sub)
{
this.name = name;
this.sub = sub;
}
public void WatchVIew()
{
Console.WriteLine("{0} {1}关闭窗口,假装写代码", sub.Subject, name);
}
}
class Client
{
static int Main(string[] args)
{
//初始化老师
Teacher Liwei = new Teacher();
//初始化同学
PlayObServer XiaoMing = new PlayObServer("小明", Liwei);
ViewObServer XiaoHong = new ViewObServer("小红", Liwei);
//监听事件
Liwei.Update += XiaoMing.PlayPhone;
Liwei.Update += XiaoHong.WatchVIew;
//老师来了一条信息
Liwei.Subject = "七点了,老师准备查班啦";
Liwei.Notify();
Console.ReadKey();
return 0;
}
}

评论列表( 0 )

你可以在登录后,对此项目发表评论

4_float_left_people 4_float_left_close