Re: [請教] bridge versus strategy pattern

作者: leondemon (狗狗)   2011-04-17 01:20:05
wiki: http://en.wikipedia.org/wiki/Strategy_pattern
"However, these two design patterns aren't the same in their intent. While
the Strategy pattern is meant for behavior, the Bridge pattern is meant for
structure."
OOD(strategy): http://www.oodesign.com/strategy-pattern.html
"Define a family of algorithms, encapsulate each one, and make them
interchangeable. Strategy lets the algorithm vary independently from
clients that use it."
OOD(bridge): http://www.oodesign.com/bridge-pattern.html
"The intent of this pattern is to decouple abstraction from implementation
so that the two can vary independently."
Strategy和Bridge兩者就UML上看起來類似 但是使用意圖卻大為不同
Stragety:
講求的是「同一類別」的物件能夠「彈性地擴充」其物件的行為 來滿足客戶的需求
也就是在不動到原本的物件的程式碼的情況下 另外創造一個物件來處理行為的演算法
而提供一個隨時可以改變的行為物件
Bridge:
講求的是在「不同類別」的物件而行為類似時 訂立一個相同interface或abstraction
這些類別在realize或subclass時 應該是以某一個特定原因去創造不同的類別
當有兩個以上的原因而需要進行subclass時 你就必須想想這兩個原因是否為獨立
若這兩個原因完全是獨立的 那麼根據SRP的原則 他們必須分開
而把這個class hierarchy有關的SRP留下 另外一個原因則獨立出來 再「橋接」在一起
也因此這兩種implementation的動機可以完全獨立進行
Strategy主要是避免一個類別利用if...else...或switch...case...的方法來選擇行為
而可避免在有新的需求時 去修改原本類別
而bridge主要訴求是將不同需要subclass的因素分散出去給不同的hierarchy
以避免單一類別被過度的subclass
strategy使用時機通常顯而易見 但bridge則有時候會讓人模糊
當你一個class會兩種以上不同的理由是否真的就一定要用bridge?
答案是不一定 因為如果你只會subclass 2-3次就解決的話
你大概會懶得搞pattern (不過我會去搞它... XD)
但是當一個class hierarchy(某類別及其徒子徒孫)被subclass的次數過於頻繁的時候
你則該考慮bridge的可行性(也就是為了因應某些特定需求 而時常需要做subclass)
或是當一個「改變」的需求出現時
你發現這個class的hierarchy有幾個subclass 需要再被subclass時
那就表示該class hierarchy的設計出現了問題 需要重新檢討和design
所以簡單的說strategy是避免去動到原本的code Bridge則是避免過度的subclass

Links booklink

Contact Us: admin [ a t ] ucptt.com