一、UML图
二、包含的角色
Implementor类,实现部分抽象出来的接口。
ConcreteImplementorA,ConcreteImplementorB为Implement派生的类,为具体的实现。
Abstraction类,抽象部分实现。
RefinedAbstraction类,提炼出来的抽象部分。
三、特点
桥接模式(Bridge),将抽象部分与它的实现部分分离,使它们都可以独立地变化。
这里并不是说,让抽象类与派生类分离,而是指,抽象类和它的派生类用来实现自己的对象。
实现系统可能有多角度分类,每一种分类都有可能变化。那么就把这种多角度分离出来,让它们独立变化,减少耦合。
四、代码实现
Implementor类
class Implementor
{
public:
virtual ~Implementor() {}
virtual void Operation() = 0;
};
ConcreteImplementorA和ConcreteImplementorB类
#pragma once
#include "Implementor.h"
#include <iostream>
using namespace std;
class ConcreteImplementorA : public Implementor {
public:
ConcreteImplementorA () {}
virtual void Operation() override
{
cout << "|" << "具体实现A的方法执行" << "|" << endl;
}
};
class ConcreteImplementorB : public Implementor {
public:
ConcreteImplementorB () {}
virtual void Operation() override
{
cout << "|" << "具体实现B的方法执行" << "|" << endl;
}
};
Abstraction类
#pragma once
#include "Implementor.h"
class Abstraction
{
public:
virtual ~Abstraction() {}
Abstraction() {}
virtual void Operation()
{
_implementor->Operation();
}
void SetImplementor(Implementor *impl)
{
_implementor =impl;
}
private:
Implementor *_implementor;
};
RefinedAbstraction类
#pragma once
#include "Abstraction.h"
#include <iostream>
using namespace std;
class RefinedAbstraction : public Abstraction
{
public:
void Operation()
{
cout << "|" << "RefinedAbstraction 方法" << "|" << endl << "->>>";
Abstraction::Operation();
}
};
调用方法
#include "Abstraction.h"
#include "Implementor.h"
#include "ConcreteImplementorA.h"
#include "ConcreteImplementorB.h"
#include "RefinedAbstraction.h"
#include <memory>
int main(int argc, char **argv)
{
std::shared_ptr<Implementor> implA(new ConcreteImplementorA());
std::shared_ptr<Implementor> implB(new ConcreteImplementorB());
std::shared_ptr<Abstraction> d1(new Abstraction());
d1->SetImplementor(implA.get());
std::shared_ptr<Abstraction> d2(new RefinedAbstraction());
d2->SetImplementor(implA.get());
std::shared_ptr<Abstraction> d3(new RefinedAbstraction());
d3->SetImplementor(implB.get());
d1->Operation();
d2->Operation();
d3->Operation();
return 0;
}