1. 程式人生 > >結構型模式之 橋接模式

結構型模式之 橋接模式

ons 希望 span public 註意事項 角色 轉換 缺點 turn

橋接模式(Bridge Pattern):將抽象部分與它的實現部分分離,使它們都可以獨立地變化。它是一種對象結構型模式,又稱為柄體(Handle and Body)模式或接口(Interface)模式。

設想如果要繪制矩形、圓形、橢圓、正方形,我們至少需要4個形狀類,但是如果繪制的圖形需要具有不同的顏色,如紅色、綠色、藍色等,此時至少有如下兩種設計方案:

  • 第一種設計方案是為每一種形狀都提供一套各種顏色的版本。
  • 第二種設計方案是根據實際需要對形狀和顏色進行組合

對於有兩個變化維度(即兩個變化的原因)的系統,采用方案二來進行設計系統中類的個數更少,且系統擴展更為方便。設計方案二即是橋接模式的應用。橋接模式將繼承關系轉換為關聯關系,從而降低了類與類之間的耦合,減少了代碼編寫量。

優點: 1、抽象和實現的分離。 2、優秀的擴展能力。 3、實現細節對客戶透明。

缺點:橋接模式的引入會增加系統的理解與設計難度,由於聚合關聯關系建立在抽象層,要求開發者針對抽象進行設計與編程。

使用場景: 1、如果一個系統需要在構件的抽象化角色和具體化角色之間增加更多的靈活性,避免在兩個層次之間建立靜態的繼承聯系,通過橋接模式可以使它們在抽象層建立一個關聯關系。 2、對於那些不希望使用繼承或因為多層次繼承導致系統類的個數急劇增加的系統,橋接模式尤為適用。 3、一個類存在兩個獨立變化的維度,且這兩個維度都需要進行擴展。

註意事項:對於兩個獨立變化的維度,使用橋接模式再適合不過了。

//步驟 1 創建橋接實現接口
class DrawAPI { public: virtual void drawCirle(int radius, int x, int y) { } DrawAPI() {} ~DrawAPI() {} DrawAPI& operator=(const DrawAPI& e) { } }; //步驟 2 創建實現了 DrawAPI 接口的實體橋接實現類 class RedCircle : public DrawAPI { public: int flag; RedCircle() { flag = 1; }
~RedCircle() {} void drawCirle(int radius, int x, int y) { cout << "Drawing Circle color: red, radius: " << radius << ", x: " << x << ", " << y << endl; } private: }; class GreenCircle : public DrawAPI { public: int flag; GreenCircle() { flag = 2; } ~GreenCircle() {} void drawCirle(int radius, int x, int y) { cout << "Drawing Circle color: green, radius: " << radius << ", x: " << x << ", " << y << endl; } private: }; //步驟 3 使用 DrawAPI 接口創建抽象類 Shape class Shape { public: DrawAPI* drawAPI; virtual void draw() { } Shape() { drawAPI = NULL; } ~Shape() {} }; //步驟 4 創建實現了 Shape 接口的實體類 class Circle :public Shape { private: int x, y, radius; public: Circle() {} Circle(int x, int y, int radius, DrawAPI* drawapit) { drawAPI = drawapit; x = x; y = y; radius = radius; } void draw() { drawAPI->drawCirle(radius,x,y); } }; int main() { GreenCircle greencircle; Circle c1(100, 100, 10, &greencircle); Shape* shape1 = &c1; RedCircle redcircle; Circle c2(100, 100, 10, &redcircle); Shape* shape2 = &c2; shape1->draw(); shape2->draw(); return 0; }

結構型模式之 橋接模式