设计模式--适配器

       意图:将一个类的接口转换成客户希望的另外一个接口。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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值