大话设计模式--适配器模式 Adapter -- C++实现实例

时间:2023-03-09 23:07:02
大话设计模式--适配器模式 Adapter -- C++实现实例

1.适配器模式: 将一个类的接口转换为客户希望的另一个接口,使得原来由于接口不能一起工作的那些类一起工作。

适配器模式一般用于希望复用一些现存的类,但是接口又与复用环境要求不一致的情况。

适配器模式分为类适配器模式和对象适配器模式。

大话设计模式--适配器模式 Adapter -- C++实现实例

应该是双方都不太容易修改的时候再使用适配器模式,这是”亡羊补牢“, 首先应该是设计要完善,再次是重构,最后才是适配器。

大话设计模式--适配器模式 Adapter -- C++实现实例

--------------------------------   比较 -------------------------------

代理模式vs适配器模式vs外观模式

Posted on 2011-05-24 17:06 李大嘴 阅读(865) 评论(0)编辑
收藏

一、定义

代理模式(Proxy):为其他对象提供一种代理以控制对这个对象的访问。

适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口,使得原本接口不兼容而不能一起工作的那些类可以一起工作。

外观模式(Facade):为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

二、理解

代理模式和适配器模式应该说很相像,但是他们的区别也很明显,代理模式和被代理者的接口是同一个,只是使用中客户访问不到被代理者,所以利用代理间接的访问,而适配器模式,是因为接口不同,为了让用户使用到统一的接口,把原先的对象通过适配器让用户统一的使用,大多数运用在代码维护的后期,或者借用第三方库的情况下,而外观模式,是大家经常无意中使用的,就是把错综复杂的子系统关系封装起来,然后提供一个简单的接口给客户使用,就类似于一个转接口,可以想象成一个漏斗,中间细的那一段,越细耦合度越低,外观模式就是为了降低耦合度。

----------------------------------------------------------------------------------

实例:

target.h target.cpp 目标接口

#ifndef TARGET_H
#define TARGET_H class Target
{
public:
Target();
void virtual request();
}; #endif // TARGET_H
#include "target.h"
#include <stdio.h> Target::Target()
{
} void Target::request()
{
printf("normal request \n");
}

adaptee.h adaptee.cpp 特殊接口

#ifndef ADAPTEE_H
#define ADAPTEE_H class Adaptee
{
public:
Adaptee();
void specificRequest();
}; #endif // ADAPTEE_H
#include "adaptee.h"
#include <stdio.h> Adaptee::Adaptee()
{
} void Adaptee::specificRequest()
{
printf("Specific request\n");
}

adapter.h adapter.cpp适配器

#ifndef ADAPTER_H
#define ADAPTER_H #include "target.h"
#include "adaptee.h" class Adapter : public Target
{
public:
Adapter();
~Adapter();
void request(); private:
Adaptee *adaptee;
}; #endif // ADAPTER_H
#include "adapter.h"

Adapter::Adapter()
{
adaptee = new Adaptee();
} Adapter::~Adapter()
{
delete adaptee;
} void Adapter::request()
{
adaptee->specificRequest();
}

main.cpp

#include <iostream>
#include "target.h"
#include "adapter.h"
using namespace std; int main()
{
cout << "Adapter test!" << endl; Target *target = new Adapter();
target->request(); return 0;
}