閱讀509 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Bridge Pattern (橋接模式)

What exactly does it mean?                                                                   

The Bridge pattern is an application of the old advice, "prefer composition over inheritance".It becomes handy when you must subclass different times in ways that are orthogonal with one another. Say you must implement a hierarchy of colored shapes. You wouldn't subclass Shape with Rectangle and Circle and then subclass Rectangle with RedRectangle, BlueRectangle and GreenRectangle and the same for Circle, would you? 

You would prefer to say that each Shape has a Colorand to implement a hierarchy of colors, and that is the Bridge Pattern.

對上麵的闡述可以這樣理解,對於Colored Shape,其實是有兩個維度的變化,一個是Color,一個是Shape,如果要在一個繼承中實現這兩個維度的變化,勢必會產生諸如RedRectangle之類的類,雖然這也符合關閉原則,但有以下缺點

1. 破壞了類的單一責任原則,RedRectangle既要負責形狀,又要負責顏色

2. 代碼難以複用,比如RedRectangle 和 RedCircle 中都需要Red,但是這個Red很難被複用

解決之道就是用組合替代繼承,用has a 替代 is a,這樣Color 和 Shape 就可以獨立變化了。 所以使用橋接模式的關鍵就在於觀察類中是否有不同維度的變化,如果有,將這些變化抽象出來,用組合的方式進行關聯。



一個典型的應用:

Graphical User Interface Frameworks

Graphical User Interface Frameworks use the bridge pattern to separate abstractions from platform specific implementation. For example GUI frameworks separate a Window abstraction from a Window implementation for Linux or Mac OS using the bridge pattern.



意圖:
   將抽象部分與實現部分分離,使它們都可以獨立的變化。——《設計模式》GOF 
結構圖:


優點:

  • Decoupling interface and implementation. An implementation is not bound permanently to an interface. The implementation of an abstraction can be configured and even switched at run-time.
  • Abstraction and Implementor hierarchies can be extended independently.

Refrence: 

https://www.oodesign.com/bridge-pattern.html

https://stackoverflow.com/questions/319728/when-do-you-use-the-bridge-pattern

https://en.wikipedia.org/wiki/Bridge_pattern


最後更新:2017-04-02 15:15:29

  上一篇:go 遞歸求子集
  下一篇:go Maven學習六之利用mvn deploy命令上傳包