码迷,mamicode.com
首页 > 其他好文 > 详细

气象站--观察者模式

时间:2016-07-28 16:17:20      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

    /* 气象站 */

    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();
        }
    }

 

气象站--观察者模式

标签:

原文地址:http://www.cnblogs.com/HelloUnity/p/5715028.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!