加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
adapter.cc 2.38 KB
一键复制 编辑 原始数据 按行查看 历史
Daniel_Du 提交于 2022-02-17 21:40 . 20220217
//适配器模式
//主要用于统一接口,通常是在代码无法统一接口或者重构时使用
#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;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化