设计模式之适配器模式

在设计模式中,适配器模式(英语:adapter pattern)有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类别自己的接口包裹在一个已存在的类中。

结构图

                                                     

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

类适配器模式结构图

                                                               

c++代码示例:

#include<iostream>
using namespace std;
// "ITarget"
class Target
{
public:
// Methods
	virtual void Request() {};
};
// "Adaptee"
class Adaptee
{
public:
// Methods
	void SpecificRequest()
	{
		cout<<"Called SpecificRequest()"<<endl;
	}
};
// "Adapter"
class Adapter : public Adaptee, public Target
{
public:
// Implements ITarget interface
	void Request()
	{
// Possibly do some data manipulation
// and then call SpecificRequest
		this->SpecificRequest();
	}
};
int main() {
// Create adapter and place a request
	Target * t = new
	Adapter();
	t->Request();
	return 0;
}
对象适配器结构图:

                                                            

c++代码示例

#include<iostream>
using namespace std;
// "ITarget"
class Target
{
public:
// Methods
	virtual void Request() {};
};
// "Adaptee"
class Adaptee
{
public:
// Methods
	void SpecificRequest()
	{
		cout<<"Called SpecificRequest()"<<endl;
	}
};
// "Adapter"
class Adapter : public Target
{
private:
	Adaptee *adaptee;
public:
	Adapter()
	{
		adaptee = new Adaptee();
	}
// Implements ITarget interface
	void Request()
	{
// Possibly do some data manipulation
// and then call SpecificRequest
		adaptee->SpecificRequest();
	}
};
int main() {
// Create adapter and place a request
	Target * t = new
	Adapter();
	t->Request();
	return 0;
}
缺省适配器c++代码实例:

#include<iostream>
using namespace std;
class Target {
public:
	virtual void f1() {};
	virtual void f2() {};
	virtual void f3() {};
};
class DefaultAdapter : public Target
{
public:
	void f1() {
	}
	void f2() {
	}
	void f3() {
	}
};
class MyInteresting :public DefaultAdapter
{
public:
	void f3() {
		cout<<"呵呵,我就对f3()方法感兴趣,别的不管了!"<<endl;
	}
};
int main() {
// Create adapter and place a request
	Target * t = new
	MyInteresting();
	t->f3();
	return 0;
}
拓展连接:

http://www.cnblogs.com/qianxudetianxia/archive/2012/02/27/2010965.html
http://liuling123.com/2013/04/object-adapter.html

http://liuling123.com/2013/04/design-pattern-adapter.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值