加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
decoration.cc 1.45 KB
一键复制 编辑 原始数据 按行查看 历史
Daniel_Du 提交于 2022-02-16 11:10 . 20220216 11:10
#include <iostream>
#include <string>
#include <memory>
//装饰模式
class Finery
{
public:
using ptr=std::shared_ptr<Finery>;
virtual void show()=0;
virtual ~Finery() {};
};
class ConcrateFinery:public Finery
{
public:
using ptr=std::shared_ptr<ConcrateFinery>;
virtual void show() override
{
std::cout<<"hello"<<std::endl;
}
virtual ~ConcrateFinery() {};
};
class Person:public Finery
{
public:
using ptr=std::shared_ptr<Person>;
Person(std::string name):m_name(name)
{}
virtual void show() override
{
std::cout<<"装扮的"<<this->m_name<<std::endl;
}
private:
std::string m_name;
};
class TShirts:public Finery
{
public:
using ptr=std::shared_ptr<TShirts>;
TShirts(Finery::ptr f)
{
m_component=f;
}
~TShirts() override{}
void show() override
{
m_component->show();
std::cout<<"穿T恤"<<std::endl;
}
private:
Finery::ptr m_component;
};
class Suits:public Finery
{
public:
using ptr=std::shared_ptr<Suits>;
Suits(Finery::ptr f)
{
m_component=f;
}
~Suits(){}
void show() override
{
m_component->show();
std::cout<<"穿西服"<<std::endl;
}
private:
Finery::ptr m_component;
};
int main(int argc, char** argv)
{
Person::ptr person(new Person("Daniel"));
TShirts::ptr shirt(new TShirts(person));
Suits::ptr suit(new Suits(shirt));
suit->show();
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化