l

2015年8月13日 星期四

為什麼Observer模式屬於低耦合?

August 06 15:07~15:59

螢幕截圖 2015-08-06 15.57.56

▲Eiffel和鍵盤產生緊密耦合關係

 

有一位鄉民在搞笑談軟工部落格留言,問了一個關於Observer模式的問題:如何能說Observer是低耦合呢?我看不太懂書上說Subject與Observer之間的耦合關係是抽象的、是微弱的。」

這個問題在GoF英文版第296頁,Consequences第一點已經有說明 :「All a subject knows is that it has a list of observers, each conforming to the simple interface of the abstract Observer class. The subject doesn't know the concrete class of any observer. Thus the coupling between subjects and observers is abstract and minimal.」。(中文版338頁:「Subject只知道有一串Observer物件,只知道每一個物件都遵循抽象類別Observer所訂之簡單介面,並不知道它們所屬的具象類別為何。因此,Subject與Observer之間的偶合關係是抽象的、是微弱的。」)

***

▼看一下Observer模式的類別圖,Subject透過Observer這個介面(interface)產生偶合關係,這種偶合關係稱為抽像耦合,是一種低程度的偶合關係。因為Subject透過抽象介面與Observer產生耦合,故稱為「抽象耦合」。這種耦合關係,與「實作耦合」相比,是微弱的(minimal)。

image

 

關於偶合與抽像耦合的說明,可以參考〈亂談軟體設計(1):Cohesion and Coupling〉與〈Design Patterns 分成三大類〉。

***

友藏內心獨白:當年我也看不懂啊XD。

沒有留言:

張貼留言