设计模式–Adapter模式(适配器模式)

来源:互联网 发布:数据分析师笔试题目 编辑:程序博客网 时间:2024/05/02 00:38

将一个类的接口转换成客户希望的另外一个接口,意思增加一个中间函数做为跳板。

Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作

角色
1 目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
2 需要适配的类(Adaptee):需要适配的类或适配者类。
3 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。

#include "stdafx.h"#include <iostream>#include <vector>using namespace std;/// <summary>/// 定义客户端期待的接口/// </summary>class Target{public:virtual void Request(){cout<<"Target:Request"<<endl;}};/// <summary>/// 定义需要适配的类/// </summary>class Adaptee{public:void Other(){cout<<"Other"<<endl;}};/// <summary>/// 定义适配器/// </summary>class Adapte:public Target{public:void Request(){Adaptee* p = new Adaptee;p->Other();//通过重写,表面上调用Request()方法,变成了实际调用Other()}};void main(){Target* target = new Adapte;target->Request();getchar();}
通过适配器,客户端可以调用同一接口,因而对客户端来说是透明的。这样做更简单、更直接、更紧凑。