设计模式之适配器模式

STL中用到了迭代器模式和适配器模式,下面是适配器模式,对应大话设计模式的第17章。

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

适配器主要应用于希望复用一些现存的类,但是又与复用环境要求不一致,且双方都不太适宜更改的情况下。

STL中的适配器模式有容器适配器stack, queue,都是复用了deque,在类里面包含了一个deque,转而将对适配器容器的调用在内部都转换成deque的操作。

适配器按照我的理解,适配器包含不能配接的类,而这个适配器可以与原系统配接,所以用适配器进行转换,而转换只是在适配器类中直接调用原来类的操作。

以下是书中的代码的C++实现:

//适配器模式:将一个类的接口转换成客户希望的另一个接口
//双方都不太容易修改的时候使用适配器模式
#include <iostream>
#include <string>
using namespace std;

//球员基类
class Player
{
public:
	Player(string name) : _name(name)
	{

	}

	virtual void Attack() = 0;
	virtual void Defense() = 0;
protected:
	string _name;
};

//前锋
class Forwards : public Player
{
public:
	Forwards(string name) : Player(name)
	{

	}

    
	void Attack()
	{
        cout << "前锋 " << _name << " 进攻" << endl;  
	}

	void Defense()
	{
		cout << "前锋 " << _name << " 防守" << endl;  
	}
};

//中锋
class Center : public Player
{
public:
	Center(string name) : Player(name)
	{

	}


	void Attack()
	{
		cout << "中锋 " << _name << " 进攻" << endl;  
	}

	void Defense()
	{
		cout << "中锋 " << _name << " 防守" << endl;  
	}
};

//后卫
class Guards : public Player
{
public:
	Guards(string name) : Player(name)
	{

	}


	void Attack()
	{
		cout << "后卫 " << _name << " 进攻" << endl;  
	}

	void Defense()
	{
		cout << "后卫 " << _name << " 防守" << endl;  
	}
};

//外籍中锋,无法和现有的类适配,需要一个翻译进行适配
class ForeignCenter 
{
public:
	ForeignCenter() : _name("")
	{

	}

	string GetName()
	{
		return _name;
	}

	void SetName(string name)
	{
		_name = name;
	}

	void Attack()
	{
		cout << "外籍中锋 " << _name << " 进攻" << endl;  
	}

	void Defense()
	{
		cout << "外籍中锋 " << _name << " 防守" << endl;  
	}

private:
	string _name;
};

//姚明的翻译,相当于adapter,将外籍中锋适应成一般的player
class Translator : public Player
{
public:
	Translator(string name) : Player(name)
	{
		wjzf.SetName(name); 
	}

	void Attack()
	{
		wjzf.Attack();
	}

	void Defense()
	{
		wjzf.Defense();
	}

private:
	ForeignCenter wjzf;
};

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

	Player *m = new Guards("麦克格雷迪");
	m->Attack();

	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、付费专栏及课程。

余额充值