1、桥接模式(Bridge),将抽象部分与它的实现部分分离,使它们都可以独立地变化。
2、什么叫抽象与它的实现分离,这并不是说,让抽象类与其派生类分离,因为这没有任何意义。实现指的是抽象类和它的派生类用来实现自己的对象。
由于实现的方式多种,桥接模式的核心意图就是把这些实现独立出来,让它们各自地变化。这样就使得每种实现的变化不会影响其他实现,从而达到应对变化的目的。
实现系统可能要多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。
UML图如下:
3、C++代码实现如下:
- #include <iostream>
- using namespace std;
- class Implementor
- {
- public:
- virtual void Operation() = 0;
- };
- class ConcreteImplementorA : public Implementor
- {
- public:
- void Operation() {
- cout << "具体实现A的方法执行" << endl;
- }
- };
- class ConcreteImplementorB : public Implementor
- {
- public:
- void Operation() {
- cout << "具体实现B的方法执行" << endl;
- }
- };
- class Abstraction
- {
- protected:
- Implementor * p_implementor;
- public:
- void SetImplementor(Implementor *);
- virtual void Operation();
- };
- void Abstraction::SetImplementor(Implementor * p_implementor) {
- Abstraction::p_implementor = p_implementor;
- }
- void Abstraction::Operation() {
- p_implementor->Operation();
- }
- class RefinedAbstraction : public Abstraction
- {
- public:
- void Operation();
- };
- void RefinedAbstraction::Operation() {
- p_implementor->Operation();
- }
- int main()
- {
- Abstraction * a = new RefinedAbstraction();
- a->SetImplementor(new ConcreteImplementorA());
- a->Operation();
- a->SetImplementor(new ConcreteImplementorB());
- a->Operation();
- return 0;
- }