VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#教程之简单的观察者模式示例分享

代码如下:

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.WriteLine();
            Console.ReadKey();
        }
    }
}

相关教程