c++设计模式之适配器模式

cpp // SwitchInterface.h #ifndef SWITCH_INTERFACE_H #define SWITCH_INTERFACE_H class SwitchInterface { public: virtual void login(const std::string& username, const std::string& password) = 0; virtual void configure(const std::string& config) = 0; virtual ~SwitchInterface() {} }; #endif // SWITCH_INTERFACE_H SwitchInterface 定义了监控系统期望的统一接口,所有的交换机设备都需要实现这个接口。 1.2 定义具体设备类 cpp // S5730.h #ifndef S5730_H #define S5730_H #include <iostream> class S5730 { public: void loginS5730(const std::string& username, const std::string& password) { std::cout << "S5730 login with username: " << username << std::endl; } void configureS5730(const std::string& config) { std::cout << "Configuring S5730 with: " << config << std::endl; } }; #endif // S5730_H cpp // S12700.h #ifndef S12700_H #define S12700_H #include <iostream> class S12700 { public: void loginS12700(const std::string& username, const std::string& password) { std::cout << "S12700 login with username: " << username << std::endl; } void configureS12700(const std::string& config) { std::cout << "Configuring S12700 with: " << config << std::endl; } }; #endif // S12700_H 1.3 定义适配器 cpp // S5730Adapter.h #ifndef S5730_ADAPTER_H #define S5730_ADAPTER_H #include "SwitchInterface.h" #include "S5730.h" class S5730Adapter : public SwitchInterface { private: S5730 s5730; public: void login(const std::string& username, const std::string& password) override { s5730.loginS5730(username, password); } void configure(const std::string& config) override { s5730.configureS5730(config); } }; #endif // S5730_ADAPTER_H cpp // S12700Adapter.h #ifndef S12700_ADAPTER_H #define S12700_ADAPTER_H #include "SwitchInterface.h" #include "S12700.h" class S12700Adapter : public SwitchInterface { private: S12700 s12700; public: void login(const std::string& username, const std::string& password) override { s12700.loginS12700(username, password); } void configure(const std::string& config) override { s12700.configureS12700(config); } }; #endif // S12700_ADAPTER_H 1.4 使用适配器 cpp // Main.cpp #include "S5730Adapter.h" #include "S12700Adapter.h" int main() { SwitchInterface* switch1 = new S5730Adapter(); switch1->login("admin", "password123"); switch1->configure("Set interface GigabitEthernet0/0/1 to up"); SwitchInterface* switch2 = new S12700Adapter(); switch2->login("admin", "password456"); switch2->configure("Set interface GigabitEthernet0/0/2 to down"); delete switch1; delete switch2; return 0; }
上一篇:前端面试笔试(一)