zoukankan      html  css  js  c++  java
  • 2019年 7月12日 观察者模式 带委托

    ---恢复内容开始---

    1.例子:神奇的猫 例子来自于 网上

    猫委托 为最开始的 还有非空判断

    public class CAT
        {
            public event Action MiaoHandler;//定义一个委托事件
            public void MiaoEvent()
            {
                Console.WriteLine("{0} 神奇的猫开始叫....", this.GetType().Name);
                if(this.MiaoHandler!=null)
                {
                    foreach (Action observer in this.MiaoHandler.GetInvocationList())
                    {
                        observer.Invoke();
                    }
                }
                Console.Read();
            }
        }

    老鼠

    public class Mouse
        {
            public void Run()
            {
                Console.WriteLine("{0} 跑了", this.GetType().Name);
            }
        }

    public class Dog
        {
            public void wang()
            {
                Console.WriteLine("{0} 汪汪汪", this.GetType().Name);
            }
        }

    小偷

    public  class Stealer
        {
            public void Hide()
            {
                Console.Write("{0} 藏起来", this.GetType().Name);
            }
        }

    婴儿

     public  class Baby
        {
            public void Cry()
            {
                Console.Write("{0} 哭了", this.GetType().Name);
            }
        }

    母亲

    public class Mother
        {
            public void Whisper()
            {
                Console.Write("{0} 开始说话", this.GetType().Name);
            }
        }

    主程序入口 实例化猫 然后把其他的都+到猫的 程序一开始 运行猫的 然后 依次运行委托事件

     class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    Console.WriteLine("*******************观察者模式事件委托实现*******************");
                    CAT cAT = new CAT();
                    cAT.MiaoHandler +=new Mouse().Run;
                    cAT.MiaoHandler += new Baby().Cry;
                    cAT.MiaoHandler += new Dog().wang;
                    cAT.MiaoHandler += new Mother().Whisper;
                    cAT.MiaoHandler += new Stealer().Hide;
                    cAT.MiaoEvent();
    
                }
                catch (Exception ex)
                {
    
                    Console.WriteLine(ex.Message);
                }
                Console.Read();
            }
        }
  • 相关阅读:
    android 上传文件到百度云
    android 学习参考
    利用SSH在本机和远程服务器之间传输文件或文件夹
    指定GPU运行python程序
    ubuntu18.04调整终端字体大小
    ubuntu18.04安装搜狗输入法
    pip install .whl文件时is not a supported wheel on this platform.解决方法
    jmeter实现mysql的增删改查
    jmeter实现天气webservice请求
    常见算法 python实现
  • 原文地址:https://www.cnblogs.com/hanzhuopeng/p/11178446.html
Copyright © 2011-2022 走看看