桥接模式定义
桥接是一种结构型设计模式,可将一个大类或一系列紧密相关的类拆分为抽象和实现两个独立的层次结构,从而能在开发时分别使用
桥接模式优缺点
优点
- 抽象与实现分离,扩展能力强
- 符合开闭原则
- 符合合成复用原则
- 其实现细节对客户透明
缺点
- 对高内聚的类使用该模式可能会让代码更加复杂
桥接模式构成与实现
构成
- 抽象部分(Abstraction)提供高层控制逻辑, 依赖于完成底层实际工作的实现对象。
- 实现部分(Implementation)为所有具体实现声明通用接口。抽象部分仅能通过在这里声明的方法与实现对象交互。抽象部分可以列出和实现部分一样的方法,但是抽象部分通常声明一些复杂行为,这些行为依赖于多种由实现部分声明的原语操作。
- 具体实现(Concrete Implementations)中包括特定于平台的代码。
- 精确抽象(Refined Abstraction)提供控制逻辑的变体。与其父类一样,它们通过通用实现接口与不同的实现进行交互。
- 通常情况下,客户端(Client)仅关心如何与抽象部分合作。但是,客户端需要将抽象对象与一个实现对象连接起来。
实例
Implementation.h:
#ifndef IMPLEMENTATION_H_
#define IMPLEMENTATION_H_
#include <string>
#include <iostream>
// 实现类接口: 颜色
class Color {
public:
virtual void bepaint(std::string pen_type, std::string name) = 0;
};
#endif // IMPLEMENTATION_H_
ConcreteImplementation.h:
#ifndef CONCRETE_IMPLEMENTATION_H_
#define CONCRETE_IMPLEMENTATION_H_
#include <string>
#include "Implementation.h"
// 具体实现类: Red
class Red : public Color {
public:
void bepaint(std::string pen_type, std::string name) override {
std::cout << pen_type << "红色的" << name << "." << std::endl;
}
};
// 具体实现类: Green
class Green : public Color {
public:
void bepaint(std::string pen_type, std::string name) override {
std::cout << pen_type << "绿色的" << name << "." << std::endl;
}
};
#endif // CONCRETE_IMPLEMENTATION_H_
Abstraction.h:
#ifndef ABSTRACTION_H_
#define ABSTRACTION_H_
#include <string>
#include "Implementation.h"
// 抽象类: Pen
class Pen {
public:
virtual void draw(std::string name) = 0;
void set_color(Color* color) {
color_ = color;
}
protected:
Color* color_;
};
#endif // ABSTRACTION_H_
RefinedAbstraction.h:
#ifndef REFINED_ABSTRACTION_H_
#define REFINED_ABSTRACTION_H_
#include <string>
#include "Abstraction.h"
// 精确抽象类: BigPen
class BigPen : public Pen {
public:
void draw(std::string name) {
std::string pen_type = "大号钢笔绘制";
color_->bepaint(pen_type, name);
}
};
// 精确抽象类: SmallPencil
class SmallPencil : public Pen {
public:
void draw(std::string name) {
std::string pen_type = "小号铅笔绘制";
color_->bepaint(pen_type, name);
}
};
#endif // REFINED_ABSTRACTION_H_
main.cpp
#include "ConcreteImplementation.h"
#include "RefinedAbstraction.h"
int main() {
system("chcp 65001");
// 客户端根据运行时参数获取对应的Color和Pen
Color* color = new Red();
Pen* pen = new SmallPencil();
pen->set_color(color);
pen->draw("太阳");
delete color;
delete pen;
system("pause");
}