观察者模式

来源:互联网 发布:lsv软件 编辑:程序博客网 时间:2021/12/08 09:00


接观察者模式的经典案例就是订阅模式

接口:

    public interface DisplayElement    {        void display();    }
    public interface Observer    {        void update(float temp,float humidity,float pressure);    }
    public interface Subject    {        void registerObserver(Observer o);        void removeObserver(Observer o);        void notifyObserver();    }
 被观察者类:
<pre name="code" class="csharp">    public class WeatherData:Subject    {        private ArrayList observers;        private float temperature;        private float humidity;        private float pressure;        public WeatherData()        {            observers = new ArrayList();        }        public void registerObserver(Observer o)        {            observers.Add(o);        }        public void removeObserver(Observer o)        {            observers.Remove(o);        }        public void notifyObserver()        {            foreach (Observer o in observers)            {                o.update(temperature,humidity,pressure);            }        }        public void measurementsChanged()        {            notifyObserver();        }        public void setMeasurement(float temp,float humidity,float pressure)        {            this.temperature = temp;            this.humidity = humidity;            this.pressure = pressure;            measurementsChanged();        }    }


客户端调用类:
<pre name="code" class="csharp">    public class CurrentConditionDisplay : Observer, DisplayElement    {        private float temperature;        private float humidity;        private float pressure;        private Subject weatherData;        public CurrentConditionDisplay(Subject weatherData)        {            this.weatherData = weatherData;            weatherData.registerObserver(this);        }        public void update(float temp, float humidity, float pressure)        {            this.temperature = temp;            this.humidity = humidity;            this.pressure = pressure;            display();        }        public void display()        {            Console.WriteLine("temp:" + temperature + ",humidity:" + humidity + ",pressure:" + pressure);        }    }

最后执行:
<pre name="code" class="csharp">        static void Main(string[] args)        {            WeatherData weatherData = new WeatherData();            CurrentConditionDisplay current = new CurrentConditionDisplay(weatherData);            weatherData.setMeasurement(2.1f, 3.5f, 5f);            CurrentConditionDisplay current2 = new CurrentConditionDisplay(weatherData);            weatherData.setMeasurement(5.1f, 3.5f, 5f);            weatherData.setMeasurement(7.1f, 6.5f, 6f);            Console.ReadKey();        }






0 0
原创粉丝点击