橋模式是一種結構型設計模式,它將抽象部分與其實現部分分離,使它們可以獨立變化。這種模式通過提供橋梁結構將抽象和實現解耦。
橋模式的結構
橋模式包含以下主要角色:
Abstraction(抽象類):定義抽象接口,維護一個指向Implementor的指針
RefinedAbstraction(擴充抽象類):擴展Abstraction定義的接口
Implementor(實現類接口):定義實現類的接口
ConcreteImplementor(具體實現類):實現Implementor接口
橋模式的優點
分離抽象接口及其實現部分
提高可擴展性,可以獨立擴展抽象和實現部分
實現細節對客戶端透明
C++ 橋模式實現示例
#include <iostream>
#include <string>// 實現類接口
class Implementor {
public:virtual ~Implementor() {}virtual std::string operationImpl() const = 0;
};// 具體實現類A
class ConcreteImplementorA : public Implementor {
public:std::string operationImpl() const override {return "ConcreteImplementorA: Here's the result on platform A.\n";}
};// 具體實現類B
class ConcreteImplementorB : public Implementor {
public:std::string operationImpl() const override {return "ConcreteImplementorB: Here's the result on platform B.\n";}
};// 抽象類
class Abstraction {
protected:Implementor* implementor_;public:Abstraction(Implementor* implementor) : implementor_(implementor) {}virtual ~Abstraction() {}virtual std::string operation() const {return "Abstraction: Base operation with:\n" + implementor_->operationImpl();}
};// 擴充抽象類
class ExtendedAbstraction : public Abstraction {
public:ExtendedAbstraction(Implementor* implementor) : Abstraction(implementor) {}std::string operation() const override {return "ExtendedAbstraction: Extended operation with:\n" + implementor_->operationImpl();}
};// 客戶端代碼
void ClientCode(const Abstraction& abstraction) {std::cout << abstraction.operation();
}int main() {Implementor* implementorA = new ConcreteImplementorA;Abstraction* abstraction = new Abstraction(implementorA);ClientCode(*abstraction);std::cout << "\n";Implementor* implementorB = new ConcreteImplementorB;Abstraction* extendedAbstraction = new ExtendedAbstraction(implementorB);ClientCode(*extendedAbstraction);delete implementorA;delete implementorB;delete abstraction;delete extendedAbstraction;return 0;
}
輸出示例
Abstraction: Base operation with:
ConcreteImplementorA: Here's the result on platform A.ExtendedAbstraction: Extended operation with:
ConcreteImplementorB: Here's the result on platform B.
UML結構圖?
橋模式的應用場景
當一個類存在兩個獨立變化的維度,且這兩個維度都需要進行擴展時
當需要避免在抽象和實現之間形成永久綁定時
當需要在運行時切換不同的實現時
橋模式在GUI開發、驅動程序開發等領域有廣泛應用,例如不同操作系統下的窗口實現