C++适配器设计模式

一、适配器模式

适配器模式:将一个类的接口转换成客户希望的另一个接口,使得原本由于接口不兼容而不能一起工作的哪些类可以一起工作。

主要解决:主要解决在软件系统中,常常要将一些"现存的对象"放到新的环境中,而新环境要求的接口是现对象不能满足的。

何时使用: 1、系统需要使用现有的类,而此类的接口不符合系统的需要。 2、想要建立一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作,这些源类不一定有一致的接口。 3、通过接口转换,将一个类插入另一个类系中。(比如老虎和飞禽,现在多了一个飞虎,在不增加实体的需求下,增加一个适配器,在里面包容一个虎对象,实现飞的接口。)

如何解决:继承或依赖(推荐)。

关键代码:适配器继承或依赖已有的对象,实现想要的目标接口。

缺点:1、过多地使用适配器,会让系统非常零乱,不易整体进行把握。比如,明明看到调用的是 A 接口,其实内部被适配成了 B 接口的实现,一个系统如果太多出现这种情况,无异于一场灾难。因此如果不是很有必要,可以不使用适配器,而是直接对系统进行重构。

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

//客户端所期待的接口基类
//实现进攻和防守
class Player
{
public:
	string name;
	Player(const string &name)
	{
		this->name = name;
	}

	virtual void attack() = 0;
	virtual void defence() = 0;
};

//无需适配的类
class Forwards : public Player
{
public:
	Forwards(const string &name) : Player(name) {}
	void attack()
	{
		cout << name << " 前锋进攻" << endl;
	}
	void defence()
	{
		cout << name << " 前锋防守" << endl;
	}
};

//无需适配的类
class Center : public Player
{
public:
	Center(const string &name) : Player(name) {}
	void attack()
	{
		cout << name << " 中锋进攻" << endl;
	}
	void defence()
	{
		cout << name << " 中锋防守" << endl;
	}
};

//无需适配器的类
class Backwards : public Player
{
public:
	Backwards(const string &name) : Player(name) {}
	void attack()
	{
		cout << name << " 后卫进攻" << endl;
	}
	void defence()
	{
		cout << name << " 后卫防守" << endl;
	}
};

//需要适配的类
class ForeignCenter
{
public:
	string name;
	ForeignCenter(const string &name)
	{
		this->name = name;
	}
	void MyAttack()
	{
		cout << name << " 外籍中锋进攻" << endl;
	}
	void MyDefence()
	{
		cout << name << " 外籍中锋防守" << endl;
	}
};

//适配器类 转换需要适配的类
class TransLator : public Player
{
private:
	ForeignCenter *fc;
public:
	TransLator(const string &name) : Player(name)
	{
		fc = new ForeignCenter(name);
	}
	void attack()
	{
		fc->MyAttack();
	}
	void defence()
	{
		fc->MyDefence();
	}
};

int main()
{
	Player *p1 = new Center("李俊宏");
	p1->attack();
	p1->defence();

	TransLator *t1 = new TransLator("姚明");
	t1->attack();
	t1->defence();
	return 0;
}

参考博客:C++ 常用设计模式
参考文档:大话设计模式

猜你喜欢

转载自blog.csdn.net/weixin_38739598/article/details/107388227