設計模式——觀察者模式

吳俊榮發表於2020-12-18

設計模式——觀察者模式

在這裡插入圖片描述
觀察者模式 定義了一種一對多的依賴關係,讓多個觀察者物件同時監聽某一個主題物件,這個主題物件在狀態發生變化時,會通知所有觀察者物件,使他們能夠自動更新自己

 ///看股票的同事
    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);
        }
    }
    //看NBA 的同事
    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直播,繼續工作!", sub.SubjectState, name);
        }
    }

    //通知者介面
    interface Subject
    {
        void Notify();

        string SubjectState
        {
            get;
            set;
        }
    }

    delegate void EventHandler();

    //老闆類 
    class Boss : Subject
    {
        //宣告一事件Update,型別為委託EventHandler
        public event EventHandler Update;

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

        public void Notify()
        {
            Update();//在訪問“通知”方法時,呼叫“更新”
        }
    }

    //前臺祕書類

    class Secretary:Subject
    {
        //宣告一事件Update,型別為委託EventHandler
        public event EventHandler Update;

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

        public void Notify()
        {
            Update();//在訪問“通知”方法時,呼叫“更新”
        }
    }
         static void Main(string[] args)
        {
                    //老闆胡漢三
            Boss huhansan = new Boss();
            //看股票的同事
            StockObserver tongshi1 = new StockObserver("魏關在", huhansan);
            //看NBA的同事
            NBAObserver tongshi2 = new NBAObserver("易管查", huhansan);

            huhansan.Update += new 觀察者模式.EventHandler(tongshi1.CloseStockMarket);
            huhansan.Update += new 觀察者模式.EventHandler(tongshi2.CloseNBADirectSeeding);

            //老闆回來
            huhansan.SubjectState = "我胡漢三回來了";

            //發出通知
            huhansan.Notify();
        }

相關文章