软件领域中的设计模式的重要性不言而喻。设计模式中运用了面向对象编程语言的重要特性:封装、继承、多态。虽然知道这些特性的定义但是并没有做到真正的理解,这样特性有什么作用?用于什么场合中等等问题,带着疑问开始学习设计模式,主要参考《大话设计模式》和《设计模式:可复用面向对象软件的基础》两本书。
适配器模式(Adapter):讲一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
在软件的开发中,也就是系统数据和行为都正确,但是接口不符时,我们希望考虑使用适配器,目的是使得控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类,但是接口又与复杂环境要求不一致的情况,比如在需要对早期代码复用一些功能等应用上很有实际价值。
适配器模式有两种类型:类适配器模式和对象适配器模式;由于类适配器模式是通过多重继承对一个借口与另一个接口进行匹配,而C#、VB.NET、java等语言不支持多重继承(C++支持),也对象就是一个类只有一个父类,这里我们学习对象适配器。
#include <iostream>
using namespace std;
class Target
{
public:
virtual void Request()
{
cout << "普通的请求" << endl;
}
};
class Adaptee
{
public:
void SpecificalRequest()
{
cout << "特殊请求" << endl;
}
};
class Adapter :public Target
{
private:
Adaptee* ada;
public:
/*这样就可以把表面上调用Request
实际是调用SpecificalRequest这就
是适配器的作用,现在接口一致*/
virtual void Request()
{
ada->SpecificalRequest();
}
Adapter()
{
ada = new Adaptee();
}
~Adapter()
{
delete ada;
}
};
//客户端:
int main()
{
Adapter * ada = new Adapter();
ada->Request();
delete ada;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Player
{
protected:
string name;
public:
Player(string strName) { name = strName; }
virtual void Attack() = 0;
virtual void Defense() = 0;
};
//前锋
class Forwards : public Player
{
public:
Forwards(string strName) :Player(strName){}
public:
virtual void Attack()
{
cout << name << "前锋进攻" << endl;
}
virtual void Defense()
{
cout << name << "前锋防守" << endl;
}
};
//后卫
class Guards : public Player
{
public:
Guards(string strName) :Player(strName){}
public:
virtual void Attack()
{
cout << name << "后卫进攻" << endl;
}
virtual void Defense()
{
cout << name << "后卫防守" << endl;
}
};
//外籍中锋
class Center : public Player
{
public:
Center(string strName) :Player(strName){}
public:
virtual void Attack()
{
cout << name << "中锋进攻" << endl;
}
virtual void Defense()
{
cout << name << "中锋防守" << endl;
}
};
//外籍中锋
class ForeignCenter : public Player
{
public:
ForeignCenter(string strName) :Player(strName){}
public:
virtual void Attack()
{
cout << name << "外籍中锋进攻" << endl;
}
virtual void Defense()
{
cout << name << "外籍中锋防守" << endl;
}
};
//为外籍中锋翻译
class TransLater : public Player
{
private:
ForeignCenter *player;
public:
TransLater(string strName) :Player(strName)
{
player = new ForeignCenter(strName);
}
virtual void Attack()
{
player->Attack();
}
virtual void Defense()
{
player->Defense();
}
};
//客户端
int main()
{
Player *p = new TransLater("小李");
p->Attack();
p->Defense();
Player *p1 = new Forwards("Jams");
p1->Attack();
p1->Defense();
Player *p2 = new Guards("KoBe");
p2->Attack();
p2->Defense();
return 0;
}