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

 

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);
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值