观察者模式
由于要将不同的独立开来,我们先添加一个接口ISubject:
public interface ISubject { void RegisterObserver(IObserver o); void RemoveObserver(IObserver o); void NotifyObserver(); }
接着我们设置一个主题WeatherData:
public class WeatherData : ISubject { private readonly ArrayList _observers; private double _temp; private double _pressure; public WeatherData() { _observers=new ArrayList(); } public void RegisterObserver(IObserver o) //添加观察者 { _observers.Add(o); } public void RemoveObserver(IObserver o) //移除观察者 { _observers.Remove(o); } public void NotifyObserver() //通知观察者 { foreach (IObserver observer in _observers) { observer.Update(_temp,_pressure); } } public void MeasurementChanged() { NotifyObserver(); } public void SetMassage(double temp, double pressure) { _temp = temp; _pressure = pressure; MeasurementChanged(); } }
由于观察者有多个,我们把他不同的独立出来为2个接口IObserver与IDisplayElement:
public interface IObserver { void Update(double temp, double pressure); } public interface IDisplayElement { void Display(); }
添加2个不同的观察者来分别不同实现独立出来的2个接口ADisplay和BDisplay:
public class ADisplay : IObserver, IDisplayElement { private double _temp; private readonly ISubject _weatherData; public ADisplay(ISubject weatherData) { _weatherData = weatherData; // weatherData.RegisterObserver(this); // weatherData.RemoveObserver(this); } public ISubject WeatherData { get { return _weatherData; } } public void Update(double temp, double pressure) { _temp = temp; Display(); } public void Display() { Console.WriteLine("Temp:"+" "+_temp); } } public class BDisplay : IObserver, IDisplayElement { private double _pressure; private readonly ISubject _weatherData; public BDisplay(ISubject weatherData) { _weatherData = weatherData; // weatherData.RegisterObserver(this); } public ISubject WeatherData { get { return _weatherData; } } public void Update(double temp, double pressure) { _pressure = pressure; Display(); } public void Display() { Console.WriteLine("Pressure:" + " " + _pressure); } }
这个时候我们就可以轻松的实现1对多的关系,也可以动态的添加和移除观察者
tatic void Main(string[] args) { var weatherData=new WeatherData(); var a = new ADisplay(weatherData); var b=new BDisplay(weatherData); weatherData.RemoveObserver(a); weatherData.RegisterObserver(a); weatherData.RemoveObserver(a); weatherData.SetMassage(11,12); weatherData.SetMassage(1, 2); weatherData.SetMassage(110, 12); Console.ReadLine(); }
结果为:
观察者的好处:
1.轻松的建立1对多的关系
2.主题可以控制观察者的数量
3.观察者可以处理主题发过来的数据,并不影响主题的数据