zoukankan      html  css  js  c++  java
  • 【设计模式】16.观察者模式

    说明:观察者有订阅和订阅者的关系,现实中的微信关注订阅,就是观察者模式。而且加上委托更方便使用。

    场景:一个类发生改变,需要通知其他类,但没有固定数目时。

    实现:

    public delegate void weituo(object sender);
    
        public class TenXun
        {
            public weituo weituo1;
    
            public string Symbol { get; set; }
            public string Info { get; set; }
            public TenXun(string _symbol,string _info)
            {
                Symbol = _symbol;
                Info = _info;
            }
    
            public void AddObserver(weituo wt)
            {
                weituo1 += wt;
            }
            public void RemoveObserver(weituo wt)
            {
                weituo1 -= wt;
            }
    
            public void Update()
            {
                if (weituo1 != null)
                {
                    weituo1(this);
                }
            }
        }
    
        public class TenXunGame : TenXun
        {
            //实际类
            public TenXunGame(string _symbol,string _info) : base(_symbol, _info)
            {
    
            }
        }
    
        public class Subscriber
        {
            public string Name { get; set; }
            public Subscriber(string name) { Name = name; }
    
            public void Print(Object obj)
            {
                TenXun tx = (TenXun)obj;
                Console.Write("{0}关注了{1}的信息:{2}", Name, tx.Symbol, tx.Info);
            }
        }
    
        public class test
        {
            public void start()
            {
                TenXun tx = new TenXunGame("鬼泣", "新用户关注");
    
                Subscriber sub1 = new Subscriber("小Q");
                Subscriber sub2 = new Subscriber("小K");
    
                //添加订阅
                tx.AddObserver(new weituo(sub1.Print));
                tx.AddObserver(new weituo(sub2.Print));
    
                tx.Update();
            }
        }
  • 相关阅读:
    xpath的几个常用规则
    xpath定位不到原因浅析
    这一代人得学习
    scrapy之Request对象
    cookie字段属性解析
    selenium中get_cookies()和add_cookie()的用法
    python中生成器generator
    swagger demo code
    ctrip-apollo
    eclipse 快捷键使用日志
  • 原文地址:https://www.cnblogs.com/laokchen/p/13544061.html
Copyright © 2011-2022 走看看