C#设计模式之观察者模式实例讲解

2019-12-26 12:12:14王旭

        {
            this.Symbol = symbol;
            this.Info = info;
        }

        // 对同一个订阅号,新增和删除订阅者的操作
        public void AddObserver(IObserver ob)
        {
            observers.Add(ob);
        }
        public void RemoveObserver(IObserver ob)
        {
            observers.Remove(ob);
        }

        public void Update()
        {
            // 遍历订阅者列表进行通知
            foreach (IObserver ob in observers)
            {
                if (ob != null)
                {
                    ob.Receive(this);
                }
            }
        }
    }

    // 具体订阅号类
    public class MyBlog : Blog
    {
        public MyBlog(string symbol, string info)
            : base(symbol, info)
        {
        }
    }

    // 订阅者接口
    public interface IObserver
    {
        void Receive(Blog tenxun);
    }

    // 具体的订阅者类
    public class Subscriber : IObserver