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



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

    }
    }
    }

  • 相关阅读:
    拖拽系列二、利用JS面向对象OOP思想实现拖拽封装
    拖拽系列一、JavaScript实现简单的拖拽效果
    CSS3中三角形及三角形组合图实现
    计算机内存管理介绍
    [Leetcode]双项队列解决滑动窗口最大值难题
    [Leetcode]827.使用回溯+标记解决最大人工岛问题
    计算机启动过程
    [Leetcode]895.最大频率栈
    GDB查看内存(x 命令)
    理解递归
  • 原文地址:https://www.cnblogs.com/zhshlimi/p/4955864.html
Copyright © 2020-2023  润新知