适配器模式——C++实现

基本概念:

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

主要内容:

(1)类适配器:

当客户在接口中定义了他期望的行为时,我们就可以应用适配器模式,提供一个实现该接口的类,并且扩展已有的类,通过创建子类来实现适配。

(2)对象适配器:

对象适配器”通过组合除了满足“用户期待接口”还降低了代码间的不良耦合。在工作中推荐使用“对象适配”。

(3) 缺省适配器模式

缺省适配器模式是一种特殊的适配器模式,但这个适配器是由一个抽象类实现的,并且在抽象类中要实现目标接口中所规定的所有方法,但很多方法的实现都是“平庸”的实现,也就是说,这些方法都是空方法。而具体的子类都要继承此抽象类。

本文主要讲述类适配器和对象适配器。

解决的问题
  即Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。

模式中的角色
 (1) 目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
 (2) 需要适配的类(Adaptee):需要适配的类或适配者类。
 (3) 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。

类适配器类图

对象适配器类图

所以,类适配是通过多重继承(Adapter继承于Adaptee和Target类)实现接口适配;而对象适配器,是通过单继承,即Adapter只继承于Target,然后,在Adapter类中创建,Adaptee对象,实现了接口适配。

Adaptee.h

#pragma once
#include<iostream>
using namespace std;
class Adaptee
{
public:
	// Methods
	void SpecificRequest()
	{
		cout<<"Called SpecificRequest()"<<endl;
	}
};

Target.h

#pragma once
class Target
{
public:
	// Methods
	virtual void Request(){};
};

main.cpp

#include"Adapter.h"
int main()
{
	// Create adapter and place a request
	Target *t = new Adapter();
	t->Request();
	return 0;
}

类适配器Adapter类

#pragma once
#include"Adaptee.h"
#include"Target.h"
class Adapter : public Adaptee, public Target
{
public:
	// Implements ITarget interface
	void Request()
	{
		// Possibly do some data manipulation
		// and then call SpecificRequest
		this->SpecificRequest();
	}
};

对象适配器Adapter类

 "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();
	}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章