1、場景:有一個氣象站,檢測氣象後發佈氣象信息,有3個觀察者會接受氣象的發佈信息。ide
2、普通的處理方式:測試
3、觀察者模式處理方式:this
OO原則:爲交互對象之間的鬆耦合設計而努力。(這個是第四條,後續還有幾條)spa
鬆耦合的設計之因此能讓咱們創建有彈性的OO系統,可以應對變化,是由於對象之間的互相依賴降到了最低。觀察者模式提供了一種對象設計,讓主題和觀察者之間鬆耦合。當兩個對象之間鬆耦合,它們依然能夠交互,可是不太清楚彼此的細節。設計
觀察者模式:在對象之間定義一對多的依賴,這樣一來,當一個對象改變狀態,依賴它的對象都會收到通知,並自動更新。code
詳細代碼關係圖與代碼以下。orm
/// <summary>
/// 主題,規定發佈者遵行的行爲 /// </summary>
public interface ISubject { /// <summary>
/// 註冊 /// </summary>
/// <param name="observer">觀察者</param>
void Register(IObserver observer); /// <summary>
/// 註銷,退出 /// </summary>
/// <param name="observer">觀察者</param>
void Logout(IObserver observer); /// <summary>
/// 通知 /// </summary>
/// <param name="info">消息內容</param>
void Notify(object info); } /// <summary>
/// 觀察者,規定訂閱者遵行的行爲 /// </summary>
public interface IObserver { /// <summary>
/// 更新 /// </summary>
/// <param name="info">要更新的信息</param>
void Update(object info); } /// <summary>
/// 氣象數據主題 /// </summary>
public class WeatherData : ISubject { private List<IObserver> observerList = new List<IObserver>(); /// <summary>
/// 數據變動狀態 /// </summary>
public bool Status { get; private set; } public Scene Info { get; set; } public void Register(IObserver observer) { observerList.Add(observer); } public void Logout(IObserver observer) { observerList.Remove(observer); } public void Notify(object info) { if (!Status) { return; } foreach (IObserver observer in observerList) { observer.Update(info); } Status = false; } public void SetChanged() { Status = true; Notify(Info); } } /// <summary>
/// 場景、環境 /// </summary>
public struct Scene { /// <summary>
/// 溫度 /// </summary>
public float Temperature { get; set; } /// <summary>
/// 溼度 /// </summary>
public float Humidity { get; set; } /// <summary>
/// 壓力 /// </summary>
public float Pressure { get; set; } public override string ToString() { return string.Format("溫度:{0},溼度:{1},壓力:{2}", Temperature, Humidity, Pressure); } } public class Observer1 : IObserver { public Observer1(ISubject subject) { subject.Register(this); } public void Update(object info) { Console.WriteLine("我是1號觀察者(張三),當前信息 {0}", info); } } public class Observer2 : IObserver { public Observer2(ISubject subject) { subject.Register(this); } public void Update(object info) { Console.WriteLine("我是2號觀察者(李四),當前信息 {0}", info); } } public class Observer3 : IObserver { public Observer3(ISubject subject) { subject.Register(this); } public void Update(object info) { Console.WriteLine("我是3號觀察者(王五),當前信息 {0}", info); } } //測試代碼
[Test] public void WeatherStation() { WeatherData weather = new WeatherData(); Observer1 observer1 = new Observer1(weather); Observer2 observer2 = new Observer2(weather); Observer3 observer3 = new Observer3(weather); Scene scene = new Scene() { Humidity = 26f, Temperature = 33f, Pressure = 29.2f }; weather.Info = scene; weather.SetChanged(); scene.Temperature = 31.5f; scene.Humidity = 28.2f; weather.Info = scene; weather.SetChanged(); }