气象站--观察者模式

    /* 气象站 */

    public interface Subject
    {
        void Regist(Observer observer);
        void Remove(Observer observer);
        void Notify();
    }

    public interface Observer
    {
        void UpDate(WeatherData weahterData);
    }

    public interface DisplayElement
    {
        void Display();
    }

    public class WeatherData : Subject
    {
        private float m_temperature;
        public float Temperature
        {
            get { return m_temperature; }
            set
            {
                if (m_temperature != value)
                {
                    m_temperature = value;
                    Notify();
                }
            }
        }

        private List<Observer> m_listObservers = new List<Observer>();
        public void Regist(Observer observer)
        {
            if (!m_listObservers.Contains(observer))
            {
                m_listObservers.Add(observer);
            }
        }
        public void Remove(Observer observer)
        {
            if (m_listObservers.Contains(observer))
            {
                m_listObservers.Remove(observer);
            }
        }
        public void Notify()
        {
            for (int i = 0; i < m_listObservers.Count; i++)
            {
                m_listObservers[i].UpDate(this);
            }
        }
    }

    public class DisplayWeatherA : DisplayElement, Observer
    {
        float Temperature;
        public void Display()
        {
            Console.WriteLine(Temperature);
        }
        public void UpDate(WeatherData weahterData)
        {
            Temperature = weahterData.Temperature;
        }
    }
    public class DisplayWeatherB : DisplayElement, Observer
    {
        float Temperature;
        public void Display()
        {
            Console.WriteLine(Temperature);
        }
        public void UpDate(WeatherData weahterData)
        {
            Temperature = weahterData.Temperature;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            DisplayWeatherA dwa = new DisplayWeatherA();
            DisplayWeatherB dwb = new DisplayWeatherB();
            WeatherData wd = new WeatherData();
            wd.Regist(dwa);
            wd.Regist(dwb);
            wd.Temperature = 32;
            dwa.Display();
            dwb.Display();
            Console.ReadKey();
        }
    }

 

posted @ 2016-07-28 15:40  贴心小冰棍  阅读(261)  评论(0编辑  收藏  举报