适配器模式

适配器模式

应用场景

  • 当你希望使用某个类, 但是其接口与其他代码不兼容时, 可以使用适配器类。

实现方式

  1. 确保至少有两个类的接口不兼容
  2. 声明客户端接口, 描述客户端如何与服务交互。
  3. 创建遵循客户端接口的适配器类。 所有方法暂时都为空。
  4. 在适配器类中添加一个成员变量用于保存对于服务对象的引用。 通常情况下会通过构造函数对该成员变量进行初始化, 但有时在调用其方法时将该变量传递给适配器会更方便。
  5. 依次实现适配器类客户端接口的所有方法。 适配器会将实际工作委派给服务对象, 自身只负责接口或数据格式的转换。
  6. 客户端必须通过客户端接口使用适配器。 这样一来, 你就可以在不影响客户端代码的情况下修改或扩展适配器。

示例代码

#include <iostream>
#include <string>
using namespace std;

class Target
{
public:
	virtual ~Target() = default;
	virtual std::string request()const
	{
		return "Target: The default target's behavior.";
	}
};

/************************************************************************/
/* adaptee 的接口和现在的客户端接口不匹配,adaptee需要一些调整才可以被客户端使用                                                                     */
/************************************************************************/
class Adaptee {
public:
	std::string SpecificRequest() const {
		return ".eetpadA eht fo roivaheb laicepS";
	}
};

/************************************************************************/
/* adapter 将adaptee的接口和target的接口兼容                                                                     */
/************************************************************************/
class Adapter : public Target {
private:
	Adaptee *adaptee_;

public:
	Adapter(Adaptee *adaptee) : adaptee_(adaptee) {}
	std::string request() const override {
		std::string to_reverse = this->adaptee_->SpecificRequest();
		std::reverse(to_reverse.begin(), to_reverse.end());
		return "Adapter: (TRANSLATED) " + to_reverse;
	}
};

void ClientCode(const Target *target) {
	std::cout << target->request();
}

int main() {
	std::cout << "Client: I can work just fine with the Target objects:\n";
	Target *target = new Target;
	ClientCode(target);
	std::cout << "\n\n";
	Adaptee *adaptee = new Adaptee;
	std::cout << "Client: The Adaptee class has a weird interface. See, I don't understand it:\n";
	std::cout << "Adaptee: " << adaptee->SpecificRequest();
	std::cout << "\n\n";
	std::cout << "Client: But I can work with it via the Adapter:\n";
	Adapter *adapter = new Adapter(adaptee);
	ClientCode(adapter);
	std::cout << "\n";

	delete target;
	delete adaptee;
	delete adapter;

	return 0;
}

posted on 2021-05-17 19:08  Ultraman_X  阅读(47)  评论(0编辑  收藏  举报

导航