觀察者模式-Observer Pattern

設計模式系列

觀察者模式:定義物件一種一對多的依賴關係,若有一個物件狀態發生改變時,所有依賴於它
                     的物件都將自動地得到通知且被更新。

優點:程式獨立不互相影響,擴充性佳,減少耦合

缺點 : 常常收到不必要的資訊

    class Program
    {
        static void Main(string[] args)
        {
            ConcreteSubject s = new ConcreteSubject();
            s.Attach(new ConcreteObserver(s, "X"));
            s.Attach(new ConcreteObserver(s, "Y"));
            s.Attach(new ConcreteObserver(s, "Z"));
            s.SubjectState = "ABC";
            s.Notify();

        }
    }

    abstract class Subject
    {
        List<Observer> observers = new List<Observer>();

        public void Attach(Observer observer)
        {
            observers.Add(observer);
        }

        public void Detach(Observer observer)
        {
            observers.Remove(observer);
        }

        public void Notify()
        {
            foreach (var o in observers)
            {
                o.Update();
            }
        }
    }

    abstract class Observer
    {
        public abstract void Update();
    }

    class ConcreteSubject:Subject
    {
        public string SubjectState { get; set; }
    }

    class ConcreteObserver:Observer
    {
        private string name;
        private string observerState;
        private ConcreteSubject subject;

        public ConcreteObserver(ConcreteSubject subject, string name)
        {
            this.subject = subject;
            this.name = name;
        }

        public override void Update()
        {
            observerState = subject.SubjectState;
            Console.WriteLine($"觀察者{name}新狀態是{observerState}");
        }

        public ConcreteSubject Subject {
            get { return subject; }
            set { subject = value; }
        }
    }

 

元哥的筆記