适配器模式: 将一个类的接口转换成另外一个期望的类的接口。适配器同意接口互不兼容的类一起工作。
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.简单的说。适配器模式就是添加一个中间层,记得有句话叫做软件开发中的一切问题都能够通过添加一个中间层来解决。
UML图例如以下:
注意Adapter和Adaptee的关系仅仅是Adapter须要Adaptee中的某些功能,而且须要遵循Target的接口。
Adapter与Target是继承层次的关系。与Adaptee是关联层次的关系。
主要包含:
Target:定义了一个客户端期望的与问题域相关的接口Adapter:和Target的接口适配的接口。即重写Target中的接口Adaptee:定义了一个须要适配的已经存在的接口。Client:和Target中的接口一起合作的类。它须要Target中的接口全部不能直接使用Adaptee中的接口。C++代码实现例如以下。
#include <stdlib.h> #include <stdio.h> #include <iostream> class Adaptee { public: void specialRequest() { std::cout<<"call specialRequest"<<std::endl; } }; class Target { public: virtual void request() { std::cout<<"call request"<<std::endl; } }; class Adapter:public Target { public: Adapter() { } Adapter(Adaptee * a) { adaptee=a; } void request() { adaptee->specialRequest(); } private: Adaptee * adaptee; }; int main() { Adaptee * ape=new Adaptee(); Target * adapter=new Adapter(ape); adapter->request(); return 0; }运行输出:
转载于:https://www.cnblogs.com/bhlsheji/p/5358285.html