假设我们有M个类,分别可以使用N个类所提供的服务,难道我们需要在M个类中实现N个函数吗? 抑或是通过冗长的if-else来判断使用的是N中哪个?这样做复杂度是MxN。我们不妨为M提供一个统一的基类,为N提供一个统一的基类,让两个基类互相关联,这样我们就将复杂度降到了M+N,就好像河东的M个村庄都到桥东,河西的N个村庄都到桥西,大家仅靠一座桥即可完成沟通,这就是桥接模式。
代码中我们这么设计一个场景,比如我们有3个设备类:笔记本,台式机,手机,又有两个标点外设类:鼠标,触摸板,如果让三个设备都可以分别使用两个外设,我们不需要每个设备类里都实现两个外设的调用,只需要把设备提升出一个基类Device, 外设提升出一个基类PointerDevice,把PointerDevice传入Device,Device调用对应的接口即可,具体的设备无需关新到底是哪个外设
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include <iostream>
class PointerDevice { public: virtual void Info() = 0; virtual ~PointerDevice() {} };
class Mouse : public PointerDevice { public: void Info() override { std::cout << "[我是一个鼠标]" << std::endl; } };
class TouchBoard : public PointerDevice { public: void Info() override { std::cout << "[我是一个触摸板]" << std::endl; } };
class Device { public: virtual ~Device() {} void InstallDriver(PointerDevice* driver) { this->driver = driver; }
virtual void GetDriverMsg() = 0; protected: PointerDevice* driver; };
class LapTop : public Device { public: void GetDriverMsg() override { std::cout << "笔记本获得驱动信息:"; driver->Info(); } }; class Desktop : public Device { public: void GetDriverMsg() override { std::cout << "台式机获得驱动信息:"; driver->Info(); } }; class HandPhone : public Device { public: void GetDriverMsg() override { std::cout << "手机获得驱动信息:"; driver->Info(); } };
int main() { PointerDevice* p1 = new Mouse; PointerDevice* p2 = new TouchBoard;
Device* d1 = new Desktop; Device* d2 = new HandPhone;
d1->InstallDriver(p1); d2->InstallDriver(p2);
d1->GetDriverMsg(); d2->GetDriverMsg();
delete p1; delete p2; delete d1; delete d2;
return 0; }
|