您的位置:首页 > 其它

【设计模式】——适配器模式

2014-07-04 00:06 330 查看
适配器模式(Adapter),将一个类的接口转换成客户端希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

  适配器模式主要解决的问题,就简单来说,需要的东西就在面前,但却不能使用,而段时间有无法改造它,于是我们就想办法适配它。在软件开发中,也就是系统的数据和行为都正确,但接口不符时,我们应该考虑用适配器,目的是是控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类,但是接口由于复用环境要求不一致的情况。

适配器模式结构图:



#include <iostream>

using namespace std;
/*Target(这是客户端所期待的接口。目标可以是具体的或抽象的类,也可以是接口)*/
class Target
{
public:
virtual void Request()
{
cout << "普通请求" << endl;
}
};
/*Adaptee(需要适配的类)*/
class Adaptee
{
public:
void SpecificRequest()
{
cout << "特殊请求" << endl;
}
};
/*Adapter通过在内部包装一个Adaptee对象,把源接口转换成目标接口*/
class Adapter:public Target
{
//建立一个私有的Adaptee对象
private:
Adaptee *adaptee=new Adaptee();
public:
//这样就可以把表面上调用Request()方法变成实际调用SpecificRequest()
void Request()
{
adaptee->SpecificRequest();
}
};
int main()
{
Target *target=new Adapter();
target->Request();
return 0;
}


何时使用适配器模式?当两个类所做的事情相同或相似,但具有不同的接口时要使用它。客户端可以统一调用统一接口,这样可以更简单、更直接、更紧凑。主要是在双方都不容易修改的时候使用适配器模式适配,而不是一有不同就使用它。

下面举个例子说明一下具体情况



#include <iostream>
using namespace std;
class Player
{
protected:
string m_name;
public:
Player(string name)
{
this->m_name=name;
}
string GetName()
{
return this->m_name;
}
virtual void Attack()=0;
virtual void Defense()=0;
};
class Forwards:public Player
{
public:
Forwards(string name):Player(name){}
void Attack()
{
cout << "前锋" << Player::GetName() << "进攻" << endl;
}
void Defense()
{
cout << "前锋" << Player::GetName() << "防守" << endl;
}
};
class Center:public Player
{
public:
Center(string name):Player(name){}
void Attack()
{
cout << "中锋" << Player::GetName() << "进攻" << endl;
}
void Defense()
{
cout << "中锋" << Player::GetName() << "防守" << endl;
}
};
class Guards:public Player
{
public:
Guards(string name):Player(name){}
void Attack()
{
cout << "后卫" << Player::GetName() << "进攻" << endl;
}
void Defense()
{
cout << "后卫" << Player::GetName() << "防守" << endl;
}
};
class ForeignCenter
{
private:
string m_name;
public:
void SetName(string name)
{
this->m_name=name;
}
string GetName()
{
return this->m_name;
}
void jingong()
{
cout << "外籍球员" << this->m_name << "进攻" << endl;
}
void fangshou()
{
cout << "外籍球员" << this->m_name << "防守" << endl;
}
};
class Translator:public Player
{
private:
ForeignCenter *wjzf=new ForeignCenter();
public:
Translator(string name):Player(name)
{
wjzf->SetName(name);
}
void Attack()
{
wjzf->jingong();
}
void Defense()
{
wjzf->fangshou();
}
};
int main()
{
Player *b=new Forwards("巴蒂尔");
b->Attack();
Player *m=new Guards("麦克格雷迪");
m->Defense();
Player *ym=new Translator("姚明");
ym->Attack();
ym->Defense();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: