【设计模式】桥接模式
桥接模式:把事物对象和其详细行为、详细特征分离开来,使它们能够各自独立的变化。事物对象仅是一个抽象的概念。如“圆形”、“三角形”归于抽象的“形状”之下,而“画圆”、“画三角”归于实现行为的“绘图”类之下,然后由“形状”调用“绘图”。“形状”成为一个继承体系,“绘图”成为还有一个继承体系,抽象和实现两者的关系为聚合关系。UML图例如以下:
- Abstraction:定义抽象的接口,该接口包括实现详细行为、详细特征的Implementor接口
- Refined Abstraction:抽象接口Abstraction的子类。依然是一个抽象的事物名
- Implementor:定义详细行为、详细特征的应用接口
- ConcreteImplementor:实现Implementor接口
以下是用C++描写叙述的桥接模式的框架:
#include <iostream>
#include <string>
using namespace std;
// 实现
class Implementor {
public:
virtual void Operation() = 0;
};
// 详细实现A
class ConcreteImplementorA : public Implementor {
public:
void Operation()
{
cout << "运行详细实现A中的方法" << endl;
}
};
// 详细实现B
class ConcreteImplementorB : public Implementor {
public:
void Operation()
{
cout << "运行详细实现B中的方法" << endl;
}
};
// 抽象
class Abstraction {
public:
void SetImplementor(Implementor *i)
{
implementor = i;
}
virtual void Operation() = 0;
~Abstraction()
{
delete implementor;
}
protected:
Implementor *implementor; // 包括一个实现
};
// 被提炼的抽象
class RefineAbstraction : public Abstraction {
public:
void Operation()
{
implementor->Operation();
}
};
int main()
{
Abstraction *ab = new RefineAbstraction();
ab->SetImplementor(new ConcreteImplementorA());
ab->Operation();
ab->SetImplementor(new ConcreteImplementorB());
ab->Operation();
// 别忘记删除指针
delete ab;
system("pause");
return 0;
}执行结果:
上面的样例实现了抽象Abstraction和实现Implementor分离。抽象中包括实现。但详细是哪种实现(ConcreteImplementorA或ConcreteImplementorB)是由client决定的。
当须要加入抽象时,仅仅须要继承Abstraction就可以。当须要加入详细实现时,继承Implementor就可以。
这样既减少了耦合度。也符合开放-封闭原则,即:功能的扩充不须要改动原来的代码而仅仅须要加入所需新的代码。
參考:
《大话设计模式》第22章
维基百科
浙公网安备 33010602011771号