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


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();

}
}
}

posted @ 2015-11-11 13:48  zslm___  阅读(265)  评论(0编辑  收藏  举报