适配器模式(adapter):将一个类的接口转换成客户希望的另外一个接口。adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
何时使用适配器模式:
两个类所做的事情相同或相似,但是具有不同的接口时需要它。
双方都不太容易修改的时候再使用适配器模式。
模式实现:
[code]//Target class Target{ public: virtual void Request(){ std::cout << "Target::Request\n"; } }; //Adaptee适配(者)的类 class Adaptee{ public: void SpecificRequest(){ std::cout << "Adaptee::SpecificRequest\n"; } }; //Adapter,适配器 class Adapter: public Target, Adaptee{ public: void Request(){ Adaptee::SpecificRequest(); } };
客户端:
[code]//Client int main(){ Target *targetObj = new Adapter(); targetObj->Request(); //Output: Adaptee::SpecificRequest delete targetObj; targetObj = NULL; return 0; }
以上就是C++设计模式浅识适配器模式的内容,更多相关内容请关注PHP中文网(www.php.cn)!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号