# Bridge ## 情境: 建立多個餐廳,而每間餐廳內還有雞肉類套餐 ![](https://i.imgur.com/9bbBMyM.png) ## 改善方法:橋接模式 ### 定義:橋接模式( Bridge ),將抽象部分與它的實現部分分離,使它們都可以獨立地變化。 ![](https://i.imgur.com/A8bwhvH.png) 餐廳階層與雞套餐階層可以靠橋接模式單獨修改 ```ruby= #Bridge class Restaurant def initialize(food) @food = food end def order "任一餐廳:\n"\ "#{@food.make}" end end class McDonald < Restaurant def order "麥當勞:\n"\ "#{@food.make}" end end class KFC < Restaurant def order "肯德基:\n"\ "#{@food.make}" end end class Napoli < Restaurant def order "拿坡里:\n"\ "#{@food.make}" end end class Chicken def make raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'" end end class ChickenThigh < Chicken def make '雞腿' end end class ChickenWing < Chicken def make '雞翅' end end class ChickenBreast < Chicken def make '雞胸' end end def client(abstraction) print abstraction.order end c_b = ChickenBreast.new r_b = Restaurant.new(c_b) client(r_b) #任一餐廳:雞胸 puts "\n\n" c_t = ChickenThigh.new m_t = McDonald.new(c_t) client(m_t) #麥當勞:雞腿 ``` ### 適用情境 1. 在需要多個平台上運行的圖型與視窗系統中使用 2. 需要在不同方式來修改介面與實作時使用 ### 優點 1. 將實作解耦合,讓他不會永遠綁定在一個介面上 2. 可以獨立擴充抽象與實作(開閉原則與單一職責) 3. 修改具體抽象類別不會影響用戶端 ### 缺點 1. 增加複雜度