zoukankan      html  css  js  c++  java
  • 进击的订阅模式

    1.需求

      草原上有 A、B 两只动物,有一只饥肠辘辘的狮子来到了草原上。

      如果狮子发现了 A,那 A 就要赶紧跑,B 可以继续猫着;如果狮子发现了 B,那 B 就要跑路,A 可以猫着;

      如果狮子把 A、B 都看到了,那 A、B 都得跑,谁知道狮子中意追哪个呢;如果狮子谁都没看见,那 A、B 都猫着。

    2.实践

      如果用传统if、else的话,业务加个C动物,那么狮子就要重新考虑,效率低、拓展性低。改用 委托+事件 完成对 狮子的订阅事件。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace 发布_订阅者模式
    {
        class Program
        {
           static void Main(string[] args)
           {
              狮子 狮子 = new 狮子();
              A a = new A(狮子);
              B b = new B(狮子);
    
              狮子.Find("A");
    
              狮子.Find("B");
    
              狮子.Find("AB");
    
              Console.ReadLine();
    
            // 由于A和B订阅了狮子的事件,所以无需任何代码,A和B均会按照约定进行动作。
          }
        }
    
        public delegate void FindEventHandler(string animals);
    
        public class 狮子
        {
             public event FindEventHandler FindEvent;
    
             public void Find(string animals)
             {
                 Console.WriteLine("狮子发现了{0}", animals);
                 if (FindEvent != null)
                 {
                     FindEvent(animals);
                 }
             }
        }
    
        public class A
        {
            public A(狮子 狮子)
            {
                狮子.FindEvent += new FindEventHandler(a_FindEvent);//订阅发现事件
            }
    
            void a_FindEvent(string animals)
            {
                if(animals.Contains("A"))
                {
                    Run();
                }
            }
    
            public void Run()
            {
                 Console.WriteLine("我是 A,被狮子发现了,我要跑了");
            }
        }
    
        public class B
        {
             public B(狮子 狮子)
             {
                  狮子.FindEvent += new FindEventHandler(b_FindEvent);//订阅发现事件
             }
    
             void b_FindEvent(string animals)
             {
                  if (animals.Contains("B"))
                  {
                      Run();
                  }
             }
    
             public void Run()
             {
                  Console.WriteLine("我是 B,被狮子发现了,我要跑了");
             }
        }
    }
  • 相关阅读:
    CVTE前端一面
    转载几篇看过的几篇使用技术博文
    Vue自定义指令
    node项目初始化的一些配置
    vue+element 实现在表格内插入其他组件,每行数据独立存储
    jquery如何实现当页面下拉到一定位置时,右下角出现回到顶部图标
    css实现垂直居中的方法整理
    css3兼容性检测工具
    css变换与动画详解
    手机访问电脑端网站偏问题解决
  • 原文地址:https://www.cnblogs.com/HansZimmer/p/11344188.html
Copyright © 2011-2022 走看看