觀察者模式——問題案例——雙耦合代碼

祕書類——Secretary

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

namespace Test_PublishOrSubscribe_Model
{
    //祕書
    class Secretary
    {
        private IList<StockObserver> observers = new List<StockObserver>();
        private string action;
        public void attch(StockObserver observer)
        {
            observers.Add(observer);
        }
        //通知-notfiy
        public void notify()
        {
            foreach (StockObserver o in observers)
            {
                o.update();
            }
        }
        //前臺狀態
        public string SecretaryAction
        {
            get { return action; }
            set { action = value; }
        }
    }
}

股票觀察者

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

namespace Test_PublishOrSubscribe_Model
{
    class StockObserver
    {
        private string name;
        private Secretary sub;
        public StockObserver(String name,Secretary sub)
        {
            this.name = name;
            this.sub = sub;
        }
        public void update()
        {
            Console.WriteLine("{0} {1} 關閉股票行情 繼續工作!",sub.SecretaryAction,name);
        }
    }
}

客戶端

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

namespace Test_PublishOrSubscribe_Model
{
    class Program
    {
        static void Main(string[] args)
        {
            Secretary secretary = new Secretary();
            StockObserver o1 = new StockObserver("強爸爸", secretary);
            StockObserver o2 = new StockObserver("強爺爺", secretary);
            secretary.attch(o1);
            secretary.attch(o2);
            secretary.SecretaryAction = "老闆回來了!!!";
            secretary.notify();
            Console.ReadKey();
        }
    }
}

總結:前臺祕書類需要增加觀察者類。觀察者類需要前臺祕書類。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章