觀察者模式Demo

using System;
using System.Collections.Generic;
 
namespace Demo
{
    #region 抽象層,定義了觀察者模式
    /// <summary>
    /// (抽象)新聞
    /// </summary>
    public interface INews
    {
        void SubScribe(ISubscriber s);
        void UnSubScribe(ISubscriber s);
        void Publish(string newsTitle);   //在具體實現的過程當中創建發佈與訂閱的聯繫
    }
 
    /// <summary>
    /// (抽象)訂閱者
    /// </summary>
    public interface ISubscriber
    {
        void Read(string newsTitle);
    }
    #endregion
 
    #region 實現層,是對抽象層的具體實現
    /// <summary>
    /// (具體)新聞
    /// </summary>
    public class ITNews : INews
    {
        private List<ISubscriber> readers = new List<ISubscriber>();
 
        public void SubScribe(ISubscriber s)
        {
            readers.Add(s);
        }
 
        public void UnSubScribe(ISubscriber s)
        {
            if (readers.Count >0)
            {
                readers.Remove(s);
            }
        }
 
        public void Publish(string newsTitle)
        {
            foreach (ISubscriber i in readers)
            {
                i.Read(newsTitle);          //<<<<<發佈的時候訂閱>>>>>
            }
        }
    }
 
    /// <summary>
    /// (具體)訂閱者
    /// </summary>
    public class Subscriber : ISubscriber
    {
        private string subscriber = string.Empty;
        public Subscriber(string subscriber)
        {
            this.subscriber = subscriber;
        }
 
        public void Read(string newsTitle)
        {
            Console.WriteLine(string.Format("{0}閱讀了IT新聞\"{1}\"", subscriber, newsTitle));
        }
    }
    #endregion
 
    public class Pro
    {
        static void Main(string[] args)
        {
            ITNews news = new ITNews();
            Subscriber zs = new Subscriber("張三"),
                                 ls = new Subscriber("李四"),
                                 ww = new Subscriber("王五");
 
            news.SubScribe(zs);
            news.SubScribe(ls);
            news.SubScribe(ww);
            news.UnSubScribe(ls);  //張三取消訂閱
 
            news.Publish("2014年移動電商攻堅戰:阿里巴巴如何破局?");
            news.Publish("餘額寶還能重回高收益率嗎?");
 
            Console.ReadKey();
        }
    }
}
相關文章
相關標籤/搜索