意图:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
适用性:
1、你想使用一个已经存在的类,但是它的接口不符合你的需求。
2、你想创建一个可以复用的类,该类可以与其他不相关的类或者不可预见的类(即那些接口可能不一定兼容的类)协同工作。
3、你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配他们的接口。对象适配器可以适配他的父类接口。
Adapter模式的结构图图示如下:
模式应用代码示例:
#include <iostream>
#include <Windows.h>
using namespace std;
/************************************************************************/
/* 类适配器 */
/************************************************************************/
//Targe
class Manipulator;
class Shape
{
public:
Shape();
public:
virtual void BoundingBox(POINT bottomLeft, POINT topRight) const;
virtual Manipulator* CreateManipulator() const;
private:
};
int main()
{
return 0;
};
//Adaptee
class TextView
{
public:
TextView();
public:
void GetOrigin(COORD& x, COORD& y) const;
void GetExtend(COORD& width, COORD& height) const;
virtual BOOL IsEmpty() const;
private:
};
//Adapter
class TextShape : public Shape, private TextView
{
public:
TextShape();
public:
virtual void BoundingBox(POINT bottomLeft, POINT topRight) const;//重写Shape接口
virtual Manipulator* CreateManipulator() const;重写Shape接口
virtual BOOL IsEmpty() const;重写TextView接口
private:
};
void TextShape::BoundingBox(POINT bottomLeft, POINT topRight) const
{
COORD bottom, left, width, height;
GetOrigin(bottom, left);
GetExtend(width, height);
bottomLeft = POINT(bottom, left);
topRight = POINT(bottom+height, left+width);
}
BOOL TextShape::IsEmpty() const
{
//直接转发请求
return TextView::IsEmpty();
}
class TextManipulator;
Manipulator* TextShape::CreateManipulator() const
{
return new TextManipulator(this);
}
/************************************************************************/
/* 对象适配器 */
/************************************************************************/
class TextShape : public Shape
{
public:
TextShape(TextView*);
public:
virtual void BoundingBox(POINT bottomLeft, POINT topRight) const;//重写Shape接口
virtual Manipulator* CreateManipulator() const;重写Shape接口
virtual BOOL IsEmpty() const;
private:
TextView* m_text;
};
TextShape::TextShape(TextView* t)
{
m_text = t;
}
void TextShape::BoundingBox(POINT bottomLeft, POINT topRight) const
{
COORD bottom, left, width, height;
m_text->GetOrigin(bottom, left);
m_text->GetExtend(width, height);
bottomLeft = POINT(bottom, left);
topRight = POINT(bottom+height, left+width);
}
BOOL TextShape::IsEmpty() const
{
return m_text->IsEmpty();
}
class TextManipulator;
Manipulator* TextShape::CreateManipulator() const
{
return new TextManipulator(this);
}