首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

設計模式實作系列(七):Bridge 橋接模式 - 將抽象與實現分離雙向獨立演化

     編輯:關於C++

模式意圖

將抽象部分與它的實現部分分離,使它們都可以獨立地變化。

UML 結構圖

Bridge Pattern UML

核心解析:聚合取代繼承

  • Abstraction: 高層抽象(如視窗、形狀),持有 Implementor* 指標。
  • Implementor: 實現介面(如繪圖 API、驅動程式),定義 OperationImpl()。
  • 關鍵: Abstraction 透過委派呼叫 Implementor,兩者各自擁有繼承體系,可獨立擴充(如新增視窗型別、新增繪圖引擎)。
  • 與 Builder 比較: 結構相似(皆聚合介面指標),但 Bridge 分離「抽象與實現」,Builder 分離「構建過程與表示」。

C++ 完整實作

1. Bridge.h

#ifndef BRIDGE_H
#define BRIDGE_H

class Implementor;
class Abstraction {
public:
    Abstraction(Implementor* pImplementor);
    virtual ~Abstraction();
    void Operation();
protected:
    Implementor* m_pImplementor;
};

class Implementor {
public:
    Implementor() {}
    virtual ~Implementor() {}
    virtual void OperationImpl() = 0;
};

class ConcreteImplementorA : public Implementor {
public:
    ConcreteImplementorA() {}
    virtual ~ConcreteImplementorA() {}
    virtual void OperationImpl();
};

class ConcreteImplementorB : public Implementor {
public:
    ConcreteImplementorB() {}
    virtual ~ConcreteImplementorB() {}
    virtual void OperationImpl();
};

#endif

2. Bridge.cpp

#include "Bridge.h"
#include <iostream>

void ConcreteImplementorA::OperationImpl() {
    std::cout << "Implementation by ConcreteImplementorA\n";
}
void ConcreteImplementorB::OperationImpl() {
    std::cout << "Implementation by ConcreteImplementorB\n";
}

Abstraction::Abstraction(Implementor* pImplementor) : m_pImplementor(pImplementor) {}
Abstraction::~Abstraction() { delete m_pImplementor; m_pImplementor = nullptr; }
void Abstraction::Operation() { m_pImplementor->OperationImpl(); }

3. Main.cpp

#include "Bridge.h"
#include <cstdlib>

int main() {
    Implementor* pImplA = new ConcreteImplementorA();
    Abstraction* pAbs1 = new Abstraction(pImplA);
    pAbs1->Operation();

    Implementor* pImplB = new ConcreteImplementorB();
    Abstraction* pAbs2 = new Abstraction(pImplB);
    pAbs2->Operation();

    delete pAbs1; delete pAbs2;
    return 0;
}

擴充:精細化抽象

可衍生 RefinedAbstraction 擴充高層功能(如 Operation2() 組合多個 OperationImpl()),不影響 Implementor 體系。

適用場景

  • 跨平台 GUI:視窗抽象(Windows/Mac/Linux)與繪圖實現(GDI/Quartz/X11)。
  • 資料庫驅動:SQL 抽象與 MySQL/PostgreSQL/Oracle 實現。
  • 訊息推送:通知抽象與 Email/SMS/Push 實現。
  • 任何「多維度變化」需獨立擴充的系統。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved