观察者(Observer)模式 行为型模式
多个对象间存在一对多关系,当一个对象发生改变时,把这种改变通知给其他多个对象,从而影响其他对象的行为。
c#
// 观察者模式示例
using System;
using System.Collections.Generic;
// 定义一个主题接口
public interface ISubject
{
void RegisterObserver(IObserver observer); // 注册观察者
void RemoveObserver(IObserver observer); // 移除观察者
void NotifyObservers(); // 通知观察者
}
// 定义一个观察者接口
public interface IObserver
{
void Update(float temperature, float humidity, float pressure); // 更新观察者状态
}
// 定义一个具体的主题类
public class WeatherData : ISubject
{
private List<IObserver> observers; // 观察者列表
private float temperature; // 温度
private float humidity; // 湿度
private float pressure; // 气压
public WeatherData()
{
observers = new List<IObserver>();
}
public void RegisterObserver(IObserver observer)
{
observers.Add(observer);
}
public void RemoveObserver(IObserver observer)
{
observers.Remove(observer);
}
public void NotifyObservers()
{
foreach (IObserver observer in observers)
{
observer.Update(temperature, humidity, pressure);
}
}
public void MeasurementsChanged()
{
NotifyObservers();
}
public void SetMeasurements(float temperature, float humidity, float pressure)
{
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
MeasurementsChanged();
}
}
// 定义一个具体的观察者类
public class CurrentConditionsDisplay : IObserver
{
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 conditions: " + temperature + "F degrees and " + humidity + "% humidity");
}
}
class Program
{
static void Main(string[] args)
{
// 创建主题对象
WeatherData weatherData = new WeatherData();
// 创建观察者对象
CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
// 设置主题状态
weatherData.SetMeasurements(80, 65, 30.4f);
}
}