观察者模式:消息的发布与订阅

来源:互联网 发布:复杂网络建模仿真工具 编辑:程序博客网 时间:2024/05/16 17:17
 

namespace YOObserver
{
    class Program
    {
        static void Main(string[] args)
        {
            ClassOver co = new ClassOver();//下课
            Teacher teacher = new Teacher("李老师", co);
            Student student = new Student("小明同学",co);
            co.Notify += new EventHandler(teacher.GoToOffice);
            co.Notify += new EventHandler(student.GoToMess);
            co.BellState = "下课铃响了";
            Console.WriteLine("下课铃响了\n");
            co.SendMessage();//将消息发出
            Console.ReadKey();
        }
    }

    //声明一个委托
    delegate void EventHandler();

    /// <summary>
    /// 通知者,消息中心;铃声接口
    /// </summary>
    interface IBell
    {
        //响铃状态
        string BellState { get; set; }
        void SendMessage();
    }

    /// <summary>
    /// 下课铃声
    /// </summary>
    class ClassOver : IBell
    {
        public event EventHandler Notify;
        private string Msg;

        #region IBell 成员

        public string BellState
        {
            get
            {
                return Msg;
            }
            set
            {
                Msg = value;
            }
        }

        public void SendMessage()
        {
            Notify();
        }

        #endregion
    }

    /// <summary>
    /// 放学铃声
    /// </summary>
    class SchoolOver : IBell
    {
        public event EventHandler Notify;
        private string Msg;
        #region IBell 成员

        public string BellState
        {
            get
            {
                return Msg;
            }
            set
            {
                Msg = value;
            }
        }

        public void SendMessage()
        {
            Notify();
        }

        #endregion
    }

    /// <summary>
    /// 教师
    /// </summary>
    class Teacher
    {
        //消息接收者
        private string name;
        private IBell iBell;

        public Teacher(string name, IBell iBell)
        {
            this.name = name;
            this.iBell = iBell;
        }

        public void GoToOffice()
        {
            Console.WriteLine("{0}   收到   {1} 消息后,去办公室",name,iBell.BellState);
        }
    }

    /// <summary>
    /// 学生
    /// </summary>
    class Student
    {
        //消息接收者
        private string name;
        private IBell iBell;

        public Student(string name, IBell iBell)
        {
            this.name = name;
            this.iBell = iBell;
        }

        public void GoToMess()
        {
            Console.WriteLine("{0}   收到   {1} 消息后,去食堂",name,iBell.BellState);
        }
    }

}

原创粉丝点击