c#观察者模式

csharp

浏览数:709

2019-1-8


Obsever.cs

//观察者模式
 interface ISubject  //抽象发布者
    {
        void Notify();
        string Subject { get; set; }
    }
    //事件委托处理
    delegate void PatrolHandler();
    class Teacher : ISubject
    {
        //事件不可以当做形参传递,但是委托可以
        public event PatrolHandler Update;
        public string Subject { get; set; }
        public void Notify()
        {
            if (Update!=null)
            {
                Update();
            }
        }
    }

    //订阅者
    class PlayObServer
    {
        private string name;
        private ISubject sub;//定义一个抽象发布者的引用
        public PlayObServer(string name,ISubject sub)
        {
            this.name = name;
            this.sub = sub;
        }

        //放下手机,假装写代码
        public void PlayPhone()
        {
            Console.WriteLine("{0} {1}放下手机,假装写代码",sub.Subject,name);
        }
    }
    class ViewObServer
    {
        private string name;
        private ISubject sub;//定义一个抽象发布者的引用
        public ViewObServer(string name, ISubject sub)
        {
            this.name = name;
            this.sub = sub;
        }
        public void WatchVIew()
        {
            Console.WriteLine("{0} {1}关闭窗口,假装写代码", sub.Subject, name);
        }
    }
    class Client
    {
        static int Main(string[] args)
        {
            //初始化老师
            Teacher Liwei = new Teacher();
            //初始化同学
            PlayObServer XiaoMing = new PlayObServer("小明", Liwei);
            ViewObServer XiaoHong = new ViewObServer("小红", Liwei);

            //监听事件
            Liwei.Update += XiaoMing.PlayPhone;
            Liwei.Update += XiaoHong.WatchVIew;
            //老师来了一条信息
            Liwei.Subject = "七点了,老师准备查班啦";

            Liwei.Notify();
 
            Console.ReadKey();
            return 0;
        }
    }