评价:这是一个战斗级别的Pattern,多用于系统整合阶段的软件设计。它形式上和Bridge类似的地方,但是很显然Adapter目标于接口转换,说白了是为了应用,基于existing的功能完成其他功能需求。
而Bridge目标于大规模的接口和实现的隔离,它使软件系统更加解藕(decouple),这是软件设计的终极目标,所以我说它是战役级别的Pattern。
适用场景:
使用已经存在的类,或者第三方的类,但是需要集成到现在的统一接口设计。
用于整合一个与现有设计不兼容的类,使用此模式来整合。
// Adapter.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Adaptee
{
public:
void SpecialMethod() const {
cout << "this is constant component without source code" << endl;
}
};
class ITarget
{
public:
virtual void Method() = 0;
};
class TargetDerive : public ITarget
{
public:
void Method() {
cout << "this is a normal derive implementation." << endl;
}
};
class TargetAdapter : public ITarget
{
// the adaptee object
Adaptee _adaptee;
public:
void Method(){
_adaptee.SpecialMethod();
}
};
int main(int argc, void* argv[])
{
TargetDerive normalDerive;
normalDerive.Method();
//Adapter client for consumer
TargetAdapter adapter;
adapter.Method();
return 0;
}