第17章适配器模式

一 概念

  • 适配器模式:将一个类的接口转换成客户希望的另外一个接口,Adapter模式使得原本由于接口不兼容而不能在一起工作的那些类可以一起工作。
  • 系统的数据和行为都正确,但接口不符时,我们应该考虑用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配,适配器模式主要应用于希望复用一些现存的类,但是接口又与复用环境不一致的情况。

二 UML图

三 C++实现代码

#include "pch.h"
#include <iostream>
#include <string>
using namespace std;

//球员的抽象类
class Player
{
public:
	virtual void Attack() = 0;
	virtual void Defense() = 0;
protected:
	string name;
};
//前锋
class Forwards : public Player
{
public:
	void Attack() override
	{
		cout << "前锋" << this->name << " 进攻" << endl;
	}
	void Defense() override
	{
		cout << "前锋" << this->name << " 防守" << endl;
	}
};
//中锋
class ForeignCenter
{
public:
	void SetName(string str)
	{
		this->name = str;
	}
	string GetName() const
	{
		return this->name;
	}
	void Attack() 
	{
		cout << "外籍中锋" << this->name << " 进攻" << endl;
	}
	void Defense() 
	{
		cout << "外籍中锋" << this->name << " 防守" << endl;
	}
private:
	string name;
};
//后卫
class Guards : public Player
{
public:
	void Attack() override
	{
		cout << "后卫" << this->name << " 进攻" << endl;
	}
	void Defense() override
	{
		cout << "后卫" << this->name << " 防守" << endl;
	}
};

//翻译者类
class Translator : public Player
{
public:
	Translator(string name)
	{
		wjzf = new ForeignCenter;
		wjzf->SetName(name);
	}
	~Translator()
	{
		delete wjzf;
	}
	void Attack() override
	{
		wjzf->Attack();
	}
	void Defense() override
	{
		wjzf->Defense();
	}
private:
	ForeignCenter* wjzf;
};

int main()
{
	Player* ym = new Translator("姚明");
	ym->Attack();
	ym->Defense();

	return 0;
}

posted @ 2019-07-03 15:43  尚修能的技术博客  阅读(155)  评论(0编辑  收藏  举报