c++设计模式概述之适配器
类写的不规范(应该屏蔽类的拷贝构造函数和运算符=)。少写点代码,缩短篇幅,重在理解。 实际中可不要这样做。
类比生活中的手机,pad等电源适配器。
简单来讲: 将原本 不匹配 的两者 变的匹配 并且 不影响 原有的逻辑结构
1、分类
A、类适配器
B、对象适配器
C、接口适配器
2、具体
A、类适配器 是通过继承(泛化)实现的。比如, 交流电220v转为5v
// 交流电 class ac220v { public: int get_output() { return 220; } }; // 直流5V class dc5v { public: virtual int get_dc_5v() = 0; }; class power_ada : public ac220v, public dc5v { public: int get_dc_5v() { int aaa = ac220v::get_output(); return 5; } }; // 调用 void call_power_ada() { std::unique_ptr<dc5v> p5v(new power_ada); if (!p5v) cout << "\n\n 类适配器创建失败\n\n"; else cout << p5v->get_dc_5v(); }
B、 对象适配器 器是通过组合来实现适配器功能的,即适配器拥有源角色的实例
class data_operation { public: void set_password(const string str) { this->str_password = str; } string get_password() { return this->str_password; } virtual string do_encrypt(const int key, const string str) = 0; private: string str_password; }; class Caesar { public: string do_encrypt(const int key, const string str) { return string("12345678"); } }; // 加密适配器类 class CipherAdapter : public Caesar, public data_operation { public: string do_encrypt(const int key, const string str) { return Caesar::do_encrypt(key, str); } }; void call_object_ada() { std::unique_ptr<data_operation> pdp(new CipherAdapter); if (!pdp) { cout << "\n\n 创建密文适配器对象失败\n\n"; return; } pdp->set_password("ABC"); string str = pdp->do_encrypt(1, string("123")); cout << "密文 = " << str.c_str(); }
C、接口适配器 , 类似pad的充电适配器一样,输出的总是恒定值, 比如,iPhone5s的手机充电线,原版充电线输出位5V。下面演示的是 输出5V,输入可以有多种的电压值的电源适配器。
// 5V接口类 class idc5v { public: virtual int output() = 0; }; // 电源接口类 class ipower { public: virtual int output() = 0; }; // 220V 电源 class ac220v : public ipower { public: int output() { return 220; } }; // 110v 电源 class ac110v : public ipower { public: int output() { return 110; } }; // 完整的电源适配器 class power_adapter : public idc5v { public: power_adapter( ac220v* pinstance) { this->_ipower = pinstance; } power_adapter( ac110v* pinstance) { this->_ipower = pinstance; } virtual ~power_adapter() { if (nullptr != _ipower) { delete _ipower; _ipower = nullptr; } } // 重写基类的函数 int output() { int ret_val = 0; if (nullptr == _ipower) cout << "\n\n\n 创建5v对象失败\n\n\n"; else { ret_val = _ipower->output(); // 省略达到5V的操作 ret_val = 5; } return ret_val; } private: ipower *_ipower = nullptr; }; // 调用电源适配器类 void call_interface_ada_demo() { ac220v* pac220 = nullptr; pac220 = new(std::nothrow) ac220v; if (nullptr == pac220) { cout << "\n\n\n 调用电源适配器: 创建220v对象失败\n\n\n"; return; } idc5v *pdc5v = new(std::nothrow) power_adapter(pac220); if (nullptr == pdc5v) { cout << "\n\n\n 调用电源适配器: 创建220v的电源适配器出错 \n\n\n"; } else { cout << "\n\n\n 调用电源适配器: 输出220v对应的适配结果:" << pdc5v->output(); } // 释放资源 if (nullptr != pdc5v) { delete pdc5v; pdc5v = nullptr; } }

浙公网安备 33010602011771号