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

Implementor* 指標。OperationImpl()。#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
#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(); }
#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 體系。