代码拉取完成,页面将自动刷新
//适配器模式
//主要用于统一接口,通常是在代码无法统一接口或者重构时使用
#include <iostream>
#include <memory>
#include <string>
//球员纯虚类
class Player
{
public:
using ptr=std::shared_ptr<Player>;
Player(const std::string& name):m_name(name){}
virtual void attack()=0;
virtual void defend()=0;
protected:
std::string m_name;
};
//前锋类
class Forward:public Player
{
public:
using ptr=std::shared_ptr<Forward>;
Forward(const std::string& name):Player(name){}
virtual void attack() override
{
std::cout<<"我是前锋-"<<m_name<<",我正在进攻"<<std::endl;
}
virtual void defend() override
{
std::cout<<"我是前锋-"<<m_name<<",我正在防守"<<std::endl;
}
};
//后卫类
class Guard:public Player
{
public:
using ptr=std::shared_ptr<Guard>;
Guard(const std::string& name):Player(name){}
virtual void attack() override
{
std::cout<<"我是后卫-"<<m_name<<",我正在进攻"<<std::endl;
}
virtual void defend() override
{
std::cout<<"我是后卫-"<<m_name<<",我正在防守"<<std::endl;
}
};
//中锋
class Center:public Player
{
public:
using ptr=std::shared_ptr<Guard>;
Center(const std::string& name):Player(name){}
virtual void attack() override
{
std::cout<<"我是中锋-"<<m_name<<",我正在进攻"<<std::endl;
}
virtual void defend() override
{
std::cout<<"我是中锋-"<<m_name<<",我正在防守"<<std::endl;
}
};
class ForeignCenter
{
public:
using ptr=std::shared_ptr<ForeignCenter>;
ForeignCenter(const std::string& name)
{
m_player=std::make_shared<Center>(name);
}
void attack()
{
std::cout<<"我翻译给他听,\"你小子听见没?旅长让你进攻\""<<std::endl;
m_player->attack();
}
void defend()
{
std::cout<<"我翻译给他听,\"你小子听见没?师长让你防守\""<<std::endl;
m_player->attack();
}
private:
Player::ptr m_player;
};
int main(int argc, char** argv)
{
Forward::ptr forward(new Forward("巴蒂尔"));
forward->attack();
forward->defend();
Guard::ptr guard(new Guard("科比"));
guard->attack();
guard->defend();
ForeignCenter::ptr chineseCenter(new ForeignCenter("姚明"));
chineseCenter->attack();
chineseCenter->defend();
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。