HeadFirst设计模式---观察者模式 C#实现
三个接口:
interface DisplayElement { void Display(); } interface Observer { void Update(float temp, float humidity, float pressure); } interface Subject { void RegisterObserver(Observer observer); void RemoveObserver(Observer observer); void NotifyObserver(); }
气象站主体:
实现subject的接口
class WeatherData : Subject { List<Observer> observers; float temperature; float humidity; float pressure; public WeatherData() { observers = new List<Observer>(); } /// <summary> /// 通知每个对象刷新数据 /// </summary> public void NotifyObserver() { int count = observers.Count; for (int i = 0; i < count; i++) { observers[i].Update(temperature,humidity,pressure); } } /// <summary> /// 注册对象 /// </summary> /// <param name="observer"></param> public void RegisterObserver(Observer observer) { observers.Add(observer); } /// <summary> /// 注销对象 /// </summary> /// <param name="observer"></param> public void RemoveObserver(Observer observer) { int index = observers.IndexOf(observer); if (index >= 0) { observers.RemoveAt(index); } } void GetTemperature() { temperature = new Random().Next(0, 40); } void GetHumidity() { humidity = new Random().Next(0, 30); } void GetPressure() { pressure = new Random().Next(0, 100); } public void MeasurementsChanged() { NotifyObserver(); } /// <summary> /// 获得新的数据,并通知所有对象 /// </summary> public void SetMeasuresments() { GetTemperature(); GetHumidity(); GetPressure(); MeasurementsChanged(); } }
观察者:布告板
实现observer和displayElement接口
class CurrentConditionsDisplay : Observer, DisplayElement { float temperature; float humidity; float pressure; Subject weatherData; public CurrentConditionsDisplay(Subject weatherData) { this.weatherData = weatherData; weatherData.RegisterObserver(this); } public void Display() { Console.WriteLine(this.ToString() + " temperature:" + temperature.ToString() + " humidity:" + humidity.ToString() + " pressure:" + pressure.ToString()); } public void Update(float temp, float humidity, float pressure) { this.temperature = temp; this.humidity = humidity; this.pressure = pressure; Display(); } }
主函数调用
class Program { static void Main(string[] args) { WeatherData weatherData = new WeatherData(); CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData); weatherData.SetMeasuresments(); weatherData.SetMeasuresments(); weatherData.RemoveObserver(currentConditionsDisplay); weatherData.SetMeasuresments(); Console.ReadKey(); } }
可以看到当主函数中把布告板注销后 再次获取数值的时候 并没有通知该布告板