适配器模式简单来说,就是提供服务方,与你想使用的接口不匹配,所以把提供服务方包一层,转为你想使用的接口
比如我们有一个手机类,它期望连接一个TypeC接口的对象,但是我们有一个USB的U盘,如何让U盘给手机提供服务呢,这时我们就需要一个适配器类USBadaptoTypeC,它把U盘封装一层然后提供一个TypeC格式的接口
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
| #include <cstddef> #include <iostream> #include <string> #include <vector>
class TypeCInterface { public: virtual std::vector<std::string> query() = 0; virtual ~TypeCInterface(){}; };
class phone { public: void ListDiskFile(TypeCInterface& device) { std::vector<std::string> files = device.query(); for(auto e : files) { std::cout << e << std::endl; } } };
class USBDisk { public: std::vector<std::string> getFile() { return m_files; } private: std::vector<std::string> m_files{"private.key", "bios.bin"}; };
class USBadaptoTypeC : public TypeCInterface { public: USBadaptoTypeC(USBDisk* disk) { m_usbdisk = disk; }
~USBadaptoTypeC() { m_usbdisk = nullptr; }
std::vector<std::string> query() override { return m_usbdisk->getFile(); } private: USBDisk* m_usbdisk; };
int main() { USBDisk myDisk;
phone myphone;
USBadaptoTypeC converter(&myDisk); myphone.ListDiskFile(converter);
return 0;
}
|