码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-观察者模式(List列表维护观察者)

时间:2015-11-11 14:36:25      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:


namespace ConsoleApplication1
{
interface IObserver
{
void ReceiveMsg(string msg);
}
class Observer : IObserver
{
string Key;
public Observer(string key)
{
this.Key = key;
}
public void ReceiveMsg(string msg)
{
Console.WriteLine("Observer-" + Key + " 收到消息:" + msg);
}
}
interface ISubject
{
void AddObserver(IObserver ob);
void DelObserver(IObserver ob);
void Notify(string msg);
}
class Subject : ISubject
{
List<IObserver> observerList = new List<IObserver>();
public void AddObserver(IObserver ob)
{
if (!observerList.Contains(ob))
observerList.Add(ob);
}
public void DelObserver(IObserver ob)
{
if (observerList.Contains(ob))
observerList.Remove (ob);
}

public void Notify(string msg)
{
foreach (IObserver ob in observerList)
{
ob.ReceiveMsg(msg);
}
}
}
class Child : Subject
{
public void Cry()
{
Notify("孩子哭了");
}
public void Smile()
{
Notify("孩子笑了");
}
}
class Program
{
static void Main(string[] args)
{
IObserver ob_father = new Observer("Father");
IObserver ob_mather = new Observer("Mather");
Child child = new Child();
child.AddObserver(ob_father);
child.AddObserver(ob_mather);
child.Cry();

Console.ReadLine();
Console.WriteLine("父亲外出国打工了..");
child.DelObserver(ob_father);
child.Smile();
Console.ReadLine();

}
}
}

设计模式-观察者模式(List列表维护观察者)

标签:

原文地址:http://www.cnblogs.com/zhshlimi/p/4955763.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!