将抽象部份与它的实现部份分离,使它们都可以独立地变化。
这里的"实现"指的是如何通过组合(委托)的方式完成用户的需求。
一.场景分析:
1.图形和颜色组合,显示不同的效果
常见的图形如:三角形,长方形,圆形。颜色有红、橙、黄、绿、蓝、淀、紫。
如果通过继承的方式,会使得颜色和形状之间的耦合性非常强,每增加一种颜色,对象的形状都需要通过集成,来派生出
形状+颜色的新类,不便于管理。
2.给电脑安装操作系统
电脑品牌很多,比如华硕,戴尔,苹果。而操作系统也很多,如Windows,Linux,Mac,Unix,
3.播放器在不同的操作系统上播放不同格式的音频
常见的音频格式有WAV,MP3,WMA, 操作系统有Windows、Linux、mac、UNIX。
4.给汽车安装发动机
二.代码
#include <iostream> #include <string> using namespace std; class Color { public: virtual string color() = 0; // 获取颜色 }; class Red : public Color { public: virtual string color() { return "红色"; } }; class Blue : public Color { public: virtual string color() { return "蓝色"; } }; class Shape { public: Shape(Color *color) :_color(color) {} public: virtual void show() = 0; protected: Color *_color; }; class Rectangle : public Shape { public: Rectangle(Color *color) :Shape(color) {} virtual void show() { cout << _color->color() << "的矩形" << endl; } }; class Circle : public Shape { public: Circle(Color *color) :Shape(color) {} virtual void show() { cout << _color->color() << "的圆形" << endl; } }; void test() { Color *red = new Red(); Color *blue = new Blue(); Shape *rect1 = new Rectangle(red); Shape *rect2 = new Rectangle(blue); Shape *circle1 = new Circle(red); Shape *circle2 = new Circle(blue); rect1->show(); rect2->show(); circle1->show(); circle2->show(); delete rect1; delete rect2; delete circle1; delete circle2; } int main() { test(); cin.get(); return 0; }
效果:
代码:
#include <iostream> #include <string> using namespace std; class OS { public: virtual void installOS() = 0; }; class WindowsOS : public OS { public: virtual void installOS() { cout << "安装windows系统" << endl; } }; class LinuxOS : public OS { public: virtual void installOS() { cout << "安装Linux系统" << endl; } }; class Computer { public: virtual void installOS(OS *os) = 0; }; class ASUSComputer : public Computer { public: virtual void installOS(OS *os) { cout << "给华硕电脑"; os->installOS(); } }; class DellComputer : public Computer { public: virtual void installOS(OS *os) { cout << "给戴尔电脑"; os->installOS(); } }; void test() { Computer *c1 = new ASUSComputer(); Computer *c2 = new DellComputer(); OS *os1 = new WindowsOS(); OS *os2 = new LinuxOS(); c1->installOS(os1); c1->installOS(os2); c2->installOS(os1); c2->installOS(os2); delete c1; delete c2; delete os1; delete os2; } int main() { test(); cin.get(); return 0; }
效果:
三、总结
桥接模式的优点 :
分离了抽象和实现。桥接模式使用了聚合代替了原本类间的绑定关系(继承具有侵入性),实现松耦合。
变化的因素之间相互隔离,独立变化,方便拓展。桥接模式在增加系统的新实现的时候,不需要修改已有类,符合开闭原则。
桥接模式的适用场景:
当继承树过于复杂时,应该考虑使用桥接模式。当一个类中存在着多个变化的维度的时候,应该考虑桥接模式。