大话设计模式17----适配器模式

大话设计模式


1 适配器模式结构图





2 对适配器模式的一些解释


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

使用场景:
  • 在想使用一个已存在的类,但是如果他的接口,也就是它的方法和你的要求不相同时,就应该考使用场景。
  • 用了适配器模式,客户代码可以统一调用统一接口就行了,这样可以更简单,更直接,更紧凑。
  • 要在双方都不太容易修改的时候再使用适配器模式适配,而不是一有不同是就使用它。

3 C++源代码实现


1 代码结构图




2 C++代码

#include<iostream>
#include<string>

using std::cout;
using std::endl;
using std::string;

class Player
{
protected:
	string name;

public:
	Player(string name)
	{
		this->name = name;
	}

	string getName()
	{
		return this->name;
	}

	void setName(string name)
	{
		this->name = name;
	}

	virtual void Attack()
	{
		cout << "进攻!" << endl;
	}

	virtual void Defense()
	{
		cout << "防守" << endl;
	}
};

class Forwards:public Player
{
public:
	Forwards(string name) :Player(name){}

	void Attack() override
	{
		cout << "前锋 " << getName() << ":进攻!!!" << endl;
	}

	void Defense() override
	{
		cout << "前锋 " << getName() << "防守!!!" << endl;
	}
};

class Center :public Player
{
public:
	Center(string name) :Player(name){}

	void Attack() override
	{
		cout << "中锋 " << getName() << ":进攻!!!" << endl;
	}

	void Defense() override
	{
		cout << "中锋 " << getName() << "防守!!!" << endl;
	}
};

class Guards :public Player
{
public:
	Guards(string name) :Player(name){}

	void Attack() override
	{
		cout << "后卫 " << getName() << ":进攻!!!" << endl;
	}

	void Defense() override
	{
		cout << "后卫 " << getName() << "防守!!!" << endl;
	}
};

class ForeignCenter
{
private:
	string name;

public:
	void setName(string name)
	{
		this->name = name;
	}

	string getName()
	{
		return this->name;
	}

	void 进攻()
	{
		cout << "外籍中锋  " << getName() << ":进攻!!!" << endl;
	}

	void 防守()
	{
		cout << "外籍中锋  " << getName() << ":防守!!!" << endl;
	}
};

class Translator :public Player
{
private:
	ForeignCenter *foreign;

public:
	Translator(string name) :Player(name)
	{
		foreign = new ForeignCenter();
		foreign->setName(name);
	}

	~Translator()
	{
		delete foreign;
		foreign = nullptr;
	}

	void Attack() override
	{
		foreign->进攻();
	}

	void Defense() override
	{
		foreign->防守();
	}
};

int main()
{
	Player *b = new Forwards("巴蒂尔");
	b->Attack();
	b->Defense();

	Player *c = new Center("麦克格雷迪");
	c->Attack();
	c->Defense();

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

	system("pause");
	return 0;
}

运行结果:
前锋 巴蒂尔:进攻!!!
前锋 巴蒂尔防守!!!
中锋 麦克格雷迪:进攻!!!
中锋 麦克格雷迪防守!!!
外籍中锋  姚明:进攻!!!
外籍中锋  姚明:防守!!!
请按任意键继续. . .





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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值