[读书笔记]观察者模式
概述
在软件构建过程中,我们需要为某些对象建立一种“通知依赖关系” ——一个对象(目标对象)的状态发生改变,所有的依赖对象(观察者对象)都将得到通知。如果这样的依赖关系过于紧密,将使软件不能很好地抵御变化。使用面向对象技术,可以将这种依赖关系弱化,并形成一种稳定的依赖关系。从而实现软件体系结构的松耦合。
意图
定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新。[GOF 《设计模式》]
此系统中的三个部分是气象站(获取实际气象数据的物理装置)、WeatherData对象(追踪来自气象站的数据,并更新布告板)和布告板(显示目前天气状况给用户看)。WeatherData对象知道如何跟物理气象站联系,以取得更新的数据。WeatherData对象会随即更新三个布告板的显示:目前状况(温度、湿度、气压)、气象统计和天气预报。

设计如下:
实现代码:
接口定义
C# Code
- public interface ISubject
- {
- void RegisterObserver(IObserver o);
- void RemoveObserver(IObserver o);
- void NotifyObservers();
- }
- public interface IObserver
- {
- void Update(float temp, float humidity, float pressure);
- }
- public interface IDisplayElement
- {
- void Display();
- }
WeatherData类的实现
C# Code
- public class WeatherData : ISubject
- {
- private List<IObserver> observers;
- private float temperature;
- private float humidity;
- private float pressure;
- public WeatherData()
- {
- if (observers == null)
- observers = new List<IObserver>();
- }
- public void RegisterObserver(IObserver o)
- {
- observers.Add(o);
- }
- public void RemoveObserver(IObserver o)
- {
- observers.Remove(o);
- }
- public void NotifyObservers()
- {
- foreach (IObserver o in observers)
- {
- o.Update(temperature, humidity, pressure);
- }
- }
- public void MeasureChanged()
- {
- NotifyObservers();
- }
- public void SetMeasurements(float temperature,
- float humidity, float pressure)
- {
- this.temperature = temperature;
- this. humidity = humidity;
- this.pressure = pressure;
- MeasureChanged();
- }
- }
CurrentConditionsDisplay类的实现:
C# Code
- public class CurrentConditionsDisplay : IObserver, IDisplayElement
- {
- private float temperature;
- private float humidity;
- private ISubject weatherData;
- public CurrentConditionsDisplay(ISubject weatherData)
- {
- this.weatherData = weatherData;
- weatherData.RegisterObserver(this);
- }
- public void Update(float temperature, float humidity,
- float pressure)
- {
- this.temperature = temperature;
- this.humidity = humidity;
- Display();
- }
- public void Display()
- {
- Console.WriteLine("Current Condition: "
- + temperature + " F degrees and "
- + humidity + " % humidity");
- }
- }
测试代码:
C# Code
- static void Main(string[] args)
- {
- WeatherData weatherData = new WeatherData();
- CurrentConditionsDisplay currentConditionDisplay
- = new CurrentConditionsDisplay(weatherData);
- weatherData.SetMeasurements(80, 65, 30.4f);
- weatherData.SetMeasurements(82, 70, 29.2f);
- weatherData.SetMeasurements(78, 90, 29.2f);
- Console.ReadLine();
- }
运行结果:

.Net Solution (VS2008) 在这里。











你的blog可是消失了好长一段时间。欢迎归来