zoukankan      html  css  js  c++  java
  • 观察者模式

    观察者模式概念:当一个事件触发的时候,同时另外几个事件也跟随触发。(狗叫了=》吓怕了小偷=》惊醒了主人)

    实现方式有很多种,这里用c#的事件委托来实现。

    第一种:原始的先建立委托,再创建事件

    namespace 观察者模式
    {
        public delegate void NotifyEventHandler(string sender);
    
        public class Cat
        {
            public event NotifyEventHandler CatEvent;
    
    
            public void Say()
            {
                Console.WriteLine("");
            }
    
            public void Cry(string info)
            {
                Console.WriteLine("猫叫了。。。");
                if (CatEvent!=null)
                {
                    CatEvent(info);
                }
            }
                 
        }
    
        public class Master
        {
            public void Wake(string name)
            {
                Console.WriteLine("惊醒了主人"+name);
            }
        }
    
        public class Mouse
        {
            public void Run(string name)
            {
                Console.WriteLine("吓跑了老鼠" + name);
            }
        }
    }
    
    
    namespace 观察者模式
    {
        class Program
        {
            static void Main(string[] args)
            {
                Cat c = new Cat();
                Master m = new Master();
                Mouse mo = new Mouse();
                c.CatEvent += new NotifyEventHandler(m.Wake);
                c.CatEvent += mo.Run;
                c.Cry(":公众部分");
    
                Console.ReadKey();
            }
        }
    }

    第二种:直接用系统定义的委托Action来定义

    namespace 观察者模式
    {
        public class Observer
        {
            public event Action<string> action;
    
            public void Run(string notify)
            {
                Console.WriteLine("狗叫了" + notify);
                if (action!=null)
                {
                    action(notify);
                }
            }
        }
    }
    
    
    namespace 观察者模式
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("=============");
                Observer os = new Observer();
                os.action += x => Console.WriteLine("惊醒了主人"+x);
                os.action += x => Console.WriteLine("吓跑了小偷"+x);
                os.Run("通知");
    
                Console.ReadKey();
            }
        }
    }
  • 相关阅读:
    ie6不支持label
    IE6下li会继承ul属性的bug、产生条件、解决办法
    玉树地震与汶川地震
    IE6给png图片添加透明级别
    使用Float布局容器高度出错的决办法
    CSS冒泡窗口,有机会改成js的
    沁园春《房》
    乱接电话的笑话~
    禁止使用英文及其缩写?
    jQuery
  • 原文地址:https://www.cnblogs.com/zhuyapeng/p/9430369.html
Copyright © 2011-2022 走看看