目录
桥接模式(Bridge Pattern)是一种【结构型】设计模式,它将抽象部分与实现部分分离,使它们可以独立地变化。这种模式通过组合而非继承来实现解耦,特别适用于需要处理多个变化维度的复杂系统。
一、模式核心概念与结构
桥接模式包含四个核心角色:
- 抽象化(Abstraction):定义抽象接口,持有实现者的引用。
- 扩展抽象化(Refined Abstraction):继承自抽象化,扩展抽象接口。
- 实现者(Implementor):定义实现接口,供具体实现者实现。
- 具体实现者(Concrete Implementor):实现实现者接口的具体类。
桥接模式的关键在于通过组合关系将抽象与实现解耦,使两者可以独立变化。
二、C++ 实现示例:图形与颜色的桥接
以下是一个经典的桥接模式示例,演示如何分离图形(抽象)和颜色(实现)的变化维度:
#include <iostream>
#include <string>
// 实现者接口:颜色
class Color
{
public:
virtual ~Color() {
}
virtual std::string fill() const = 0;
};
// 具体实现者:红色
class Red : public Color
{
public:
std::string fill() const override
{
return "Red";
}
};
// 具体实现者:蓝色
class Blue : public Color
{
public:
std::string fill() const override
{
return "Blue";
}
};
// 抽象化:图形
class Shape
{
protected:
Color* color; // 持有实现者的引用
public:
Shape(Color* c) : color(c) {
}
virtual ~Shape() {
}
virtual void draw() const = 0;
};
// 扩展抽象化:圆形
class Circle : public Shape
{
private: