大话设计模式
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;
}
前锋 巴蒂尔:进攻!!!
前锋 巴蒂尔防守!!!
中锋 麦克格雷迪:进攻!!!
中锋 麦克格雷迪防守!!!
外籍中锋 姚明:进攻!!!
外籍中锋 姚明:防守!!!
请按任意键继续. . .