观察者模式——利用委托改善

看股票的同事

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PublishOrSubrecribeInVector
{
    class StockObserver
    {
        private string name;
        private Subject sub;
        public StockObserver(string name,Subject sub)
        {
            this.name = name;
            this.sub = sub;
        }
        public void CloseStockMarket()
        {
            Console.WriteLine("{0} {1}关闭股票行情! 继续工作!!",sub.SubjectState,name);
        }
    }
    class NBAObserver
    {
        private string name;
        private Subject sub;
        public NBAObserver(string name,Subject sub)
        {
            this.name = name;
            this.sub = sub;
        }
        public void CloseNBADirectSeeding()
        {
            Console.WriteLine("{0} {1}关闭NBA直播,继续工作!!",name,sub.SubjectState);
        }

    }
}

通知者接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PublishOrSubrecribeInVector
{
    interface Subject
    {
        void Notify();
        string SubjectState
        {
            get;
            set;
        }
    }
}

Boss实现通知者接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PublishOrSubrecribeInVector
{
    delegate void EventHandler();
    class Boss : Subject
    {
        public event EventHandler Update;
        private string action;
        public void Notify()
        {
            Update();
        }

        public string SubjectState
        {
            get { return action; }
            set { action = value; }
        }
    }
}

客户端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PublishOrSubrecribeInVector
{
    class Program
    {
        static void Main(string[] args)
        {
            Boss boss = new Boss();
            StockObserver tongshi1 = new StockObserver("强爸爸", boss);
            boss.Update += new EventHandler(tongshi1.CloseStockMarket);

            boss.SubjectState = "老板回来了!!!";
            boss.Notify();
            Console.ReadKey();
        }
    }
}

原创文章 37 获赞 11 访问量 2776

猜你喜欢

转载自blog.csdn.net/qq_39691716/article/details/104180674