23种设计模式(C++)之 桥接(Bridge)模式
23种设计模式(C++)之 桥接(Bridge)模式
意图
将抽象部分与它的实现部分分离,使它们都可以独立地变化。
场景
比如,画图工具中铅笔的粗细和颜色。假设有三种粗细(0.5mm, 0.8mm, 1.0mm)和四种颜色(红,黄,蓝,黑),如果粗细与颜色合在一起,我们则需要准备十二个类来实现所有情况;如果粗细与颜色分开,我们只需要准备七个类即可实现所有情况。
角色
- Abstraction:
- 定义抽象类的接口
- 维护一个指向Implementor类型对象的指针
- RefinedAbstraction
- 扩充由Abstraction定义的接口。
- Implementor
- 定义实现类的接口, 供RefinedAbstraction调用。该接口不一定要与Abstraction的接口完全一致。一般,Implementor接口仅提供基本操作,而Abstraction则定义了基于这些操作的较高层次的操作。
- ConcreteImplementor
- 实现Implementor 接口并定义它的具体实现。
实例
以车为例,车可分为电动车和油动车,又可分为白色车和黑色车。
- 定义实现类接口
class CarColor
{
public:
virtual void setCarColor() = 0;
};
- 定义实现类
class WhiteCar : public CarColor
{
void setCarColor()
{
cout << "I'm white" << endl;
}
};
class BlackCar : public CarColor
{
void setCarColor()
{
cout << "I'm black" << endl;
}
};
- 抽象类接口
class Car
{
protected:
CarColor *carColor;
public:
virtual void showCar() = 0;
void setCarColorClass(CarColor *carColor)
{
this->carColor = carColor;
}
};
- 扩充抽象类接口
class ElectricCar : public Car
{
void showCar()
{
cout << "I'm an electric car and ";
this->carColor->setCarColor();
}
};
class OilCar : public Car
{
void showCar()
{
cout << "I'm an oil car and ";
this->carColor->setCarColor();
}
};
- 测试
int main()
{
CarColor *white = new WhiteCar();
CarColor *black = new BlackCar();
Car *electricCar = new ElectricCar();
Car *oilCar = new OilCar();
// electric with white
electricCar->setCarColorClass(white);
electricCar->showCar();
// electric with black
electricCar->setCarColorClass(black);
electricCar->showCar();
// oil with white
oilCar->setCarColorClass(white);
oilCar->showCar();
// oil with black
oilCar->setCarColorClass(black);
oilCar->showCar();
}
- 结果
I'm an electric car and I'm white
I'm an electric car and I'm black
I'm an oil car and I'm white
I'm an oil car and I'm black
来源:CSDN
作者:小生1992
链接:https://blog.csdn.net/u012409346/article/details/102576248