【設計模式】Bridge

前言

Bridge設計模式,將一個複雜類分紅能夠單獨開發的部分。分紅的兩個部分,abstraction,implementation。字面上是抽象和實現,但不一樣於抽象方法及其實現。下面摘錄Wiki的兩句話。設計模式

decouple an abstraction from its implementation so that the two can vary independently設計

這句話,講的是這個模式的定義。Bridge將abstraction從implementation中抽取出來,讓abstraction和implementation這兩個部分能夠單獨的變化。code

The class itself can be thought of as the abstraction and what the class can do as the implementation.blog

這句話太精髓了!複雜類究竟該怎麼分紅兩個部分?這句話給出了回答。一部分是咱們看這個類應該是怎麼樣子的,另外一部分是它能夠作什麼。ip

例子

下面改一改來自[1]的回答。開發

When:get

----Animal----
         /            \
      Dog              Cat
    /     \          /     \
RunDog  SleepDog RunDog SleepDog

Refactor to:博客

----Animal----                    Behavior
        /            \                     /   \
Dog(Behavior)   Cat(Behavior)           Run   Sleep

應用場景

  1. 當須要運行時更改implementation的時候。和Strategy相似,可是這兩個模式所解決的問題是不同的。
  2. 當一個類的變化處在兩個維度,一個類違反了單一職責原則的時候。

總結it

這篇博客太水了。io

參考

  1. https://stackoverflow.com/questions/319728/when-do-you-use-the-bridge-pattern-how-is-it-different-from-adapter-pattern
  2. https://en.wikipedia.org/wiki/Bridge_pattern
相關文章
相關標籤/搜索