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();
            }
        }
  • 相关阅读:
    <LinkedList> 61
    <LinkedList> (hard + 高)25
    <DP> (高频)322
    <BackTracking> (dfs hard) 291
    <Tree> (高频)236
    <Math> 29 365
    <String> 161 358
    <Array> 309 (高)334
    <Array> 54 (高频+hard )45
    <Design> 359 346
  • 原文地址:https://www.cnblogs.com/laokchen/p/13544061.html
Copyright © 2011-2022 走看看