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

观察者模式(委托与事件实现)

时间:2015-11-11 14:35:32      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:


namespace ObserverPatternDelegateEvent
{

public delegate void ObserverNotify (string key,string msg);
public abstract class Subject
{
ObserverNotify ObserverNotifyEvent;
public void AddObserver(ObserverNotify _ob)
{
this.ObserverNotifyEvent += _ob;
}
public void DelObserver(ObserverNotify _ob)
{
this.ObserverNotifyEvent -= _ob;
}
public void Notify(string key,string msg )
{
if (ObserverNotifyEvent != null)
ObserverNotifyEvent(key,msg );
}
}
public class Child : Subject
{
public string Name;
public Child(string name)
{
Name=name ;
}
public void Cry()
{
Notify(Name,"孩子"+Name+"哭了");
}
public void Smile()
{
Notify(Name, "孩子" + Name + "笑了");
}
}

public interface IObserver
{
void ReceiveMessage(string key, string msg);
}
public class Observer : IObserver
{
string role;
List<Child> ChildList = null;
public Observer(string role)
{
this.role = role;
ChildList = new List<Child>();
}
public void AddChild(Child kid)
{
ChildList.Add(kid);
kid.AddObserver(ReceiveMessage);
}
public void ReceiveMessage(string key,string msg)
{
Child kid=ChildList.Find( delegate(Child c)
{
return c.Name == key;

});
Console.WriteLine("Observer-" + role + " 收到消息:"+msg);
}
}
class Program
{
static void Main(string[] args)
{
Child k1 = new Child("张一");
Child k11 = new Child("张二");
Child k2 = new Child("李二");
Observer k1_parent = new Observer("k1_parent");
Observer k2_parent = new Observer("k2_parent");
k1_parent.AddChild(k1);
k1_parent.AddChild(k11);
k2_parent.AddChild(k2);
 
k1.Cry();
k11.Smile();
k2.Cry();
Console.ReadLine();
Console.WriteLine("李二被寄养到 k1_parent家了");
k1_parent.AddChild(k2);
k2.Cry();
Console.ReadLine();

}
}
}

观察者模式(委托与事件实现)

标签:

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

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