前言 :
在 Head-First Design Pattern 第二章接著介紹 Observer Pattern, 首先我們來看看它是怎麼介紹這個Pattern :
Don't miss out when something interesting happens! We've got a pattern that keeps your objects in the know when something they might care about happens. Objects can even decide at runtime whether they want to be kept informed. The Observer Pattern is one of the most heavily used patterns in the JDK, and it's incredibly useful. Before we're done, we'll also look at one to many relationships and loose coupling. With Observer, you'll be the life of Patterns Party.
另外這裡也有提出一些設計原則 :
* Design Principe
- Strive for loosely coupled designs between objects that interact.
Observer Pattern 定義 :
The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.
UML 示意圖 :
範例說明 :
在書中, 作者舉了一個氣象局RSS 的例子, 考慮以有一個WeatherData 物件可以提供相關氣象訊息, 並且它提供一支API:measurementsChanged 當氣象數據變更時, 這支API 就會被Callback. 而我們要作的就是當Callback 時, 則取出變化的氣象數據並顯示到Displays 上 (Display 可以是多個). 粗略示意圖如下 :
為了能夠動態增加Display devices 而在遵守設計原則 "OCP" (對修改封閉;對擴充開放), 可以聯想到報紙訂閱的流程 :
1. You subscribe to a particular publisher, and every time there's a new edition it gets delivered to you. As long as you remain a subscriber, you get new newspapers.
2. You unsubscribe when you don't want papers anymore, and they stop being delivered.
3. While the publisher remains in business, people, hotels, airlines and other businesses constantly subscribe and unsubscribe to the newspaper.
如果你懂怎麼訂閱報紙, 那麼觀察者模式就是 :
Publishers + Subscribers = Observer Pattern
其中publisher 就是 SUBJECT, 而 subscribers 就是 OBSERVERS.
範例代碼 :
請參考下面 UML 示意圖 : (詳細代碼請參考附件)
* WeatherStation 類別代碼 :
- package hf.dp.ch02;
-
- public class WeatherStation {
- public static void main(String args[]) {
- WeatherData wd = new WeatherData();
- CurrentConditionDisplay ccDisplay = new CurrentConditionDisplay(wd);
- wd.setMeasurement(55, 90, 12);
- wd.setMeasurement(60, 89, 15);
- ccDisplay.unSubscribe();
- wd.setMeasurement(71, 92, 17);
- }
- }
執行結果 :
Current Condition: 55.0 F degress & 90.0% humidity
Current Condition: 60.0 F degress & 89.0% humidity <第三次State Change, 因為Observer 已經Unsubscribe, 所以不會顯示>
補充說明 :
* Wiki on Observer Pattern :
The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
* 史帝芬心得筆記 : Design Pattern - Observer
Observer的目的在於定義一對多的物件依存關係,讓物件狀態一有變動,就自動通知其他相依物件做該做的更新動作,這個Pattern可以說是MVC的基礎架構。我自己第一次使用它是用在電子郵件認證,當系統收到使用者回覆的email時,通知所有相關物件處理後續事項; 第二次使用是在電腦象棋中,當電腦決定出下一著手時,通知棋盤、棋著列表和歷史棋著儲存區更新狀態。這是個常有機會用到的Pattern,學會了一定會受益良多。在 Observer裡的update是NumberGenerator用來通知Observer,內容已被更新的method
沒有留言:
張貼留言