8.桥接模式
设计模式——桥接模式
一、基本概念
1. 定义
**桥接模式(Bridge)**是软件设计模式中最复杂的模式之一,它把事物对象和其具体行为、具体特征分离开来,使它们可以各自独立的变化。
2. 优缺点
优点:
- 抽象与实现分离,扩展能力强;
- 符合开闭原则;
- 符合合成复用原则;
- 其实现细节对客户透明。
缺点:
- 由于聚合关系建立在抽象层,要求开发者针对抽象化进行设计与编程,能正确地识别出系统中两个独立变化的维度,这增加了系统的理解与设计难度。
3. 结构
桥接(Bridge)模式包含以下主要角色:
- 抽象化(Abstraction)角色:定义抽象类,并包含一个指向实现化对象的指针。
- 扩展抽象化(Refined Abstraction)角色:是抽象化角色的子类,实现父类中的业务方法,并通过组合关系调用实现化角色中的业务方法。
- 实现化(Implementor)角色:定义实现化角色的接口,供扩展抽象化角色调用。
- 具体实现化(Concrete Implementor)角色:给出实现化角色接口的具体实现。
classDiagram
class Abstraction {
<<abstract>>
-Implementor impl
+operation() void
}
class RefinedAbstraction {
+operation() void
}
class Implementor {
<<abstract>>
+operationImpl() void
}
class ConcreteImplementorA {
+operationImpl() void
}
class ConcreteImplementorB {
+operationImpl() void
}
Abstraction <|-- RefinedAbstraction
Implementor <|.. ConcreteImplementorA
Implementor <|.. ConcreteImplementorB
Abstraction o--> Implementor : 桥接
二、代码实现
UML
classDiagram
class Shape {
<<abstract>>
-Color color
+draw() void
}
class Circle {
+draw() void
}
class Square {
+draw() void
}
class Color {
<<abstract>>
+applyColor() void
}
class Red {
+applyColor() void
}
class Green {
+applyColor() void
}
Shape <|-- Circle
Shape <|-- Square
Color <|-- Red
Color <|-- Green
Shape o--> Color : 桥接
实现角色
颜色接口:
class Color {public: virtual ~Color() = default; virtual void fillColor(const std::string& shape) = 0;};具体实现化角色
红色:
class Red : public Color {public: void fillColor(const std::string& shape) override { std::cout << "绘制红色的" << shape << std::endl; }};绿色:
class Green : public Color {public: void fillColor(const std::string& shape) override { std::cout << "绘制绿色的" << shape << std::endl; }};抽象化角色
形状类,提供一个画形状的接口,并包含一个颜色的实例:
class Shape {public: Shape(std::unique_ptr<Color> color) : color(std::move(color)) {} virtual ~Shape() = default; virtual void drawShape() = 0;
protected: std::unique_ptr<Color> color;};拓展抽象化角色
圆形:
class Circle : public Shape {public: Circle(std::unique_ptr<Color> color) : Shape(std::move(color)) {}
void drawShape() override { color->fillColor("圆形"); }};正方形:
class Square : public Shape {public: Square(std::unique_ptr<Color> color) : Shape(std::move(color)) {}
void drawShape() override { color->fillColor("正方形"); }};客户类
#include <iostream>#include <memory>#include <string>
int main() { std::unique_ptr<Color> green = std::make_unique<Green>(); std::unique_ptr<Shape> circle = std::make_unique<Circle>(std::move(green)); circle->drawShape();
std::unique_ptr<Color> red = std::make_unique<Red>(); std::unique_ptr<Shape> square = std::make_unique<Square>(std::move(red)); square->drawShape(); return 0;}运行结果:
绘制绿色的圆形绘制红色的正方形参考:
Thanks for reading!