C++设计模式——装饰着模式(高屋建瓴)

原网址:
https://blog.csdn.net/anqiu4023/article/details/102275902

#include <iostream>
#include<string>
using namespace std;
//person 类
class Person {
public:
Person(){}
Person(std::string name);
virtual void Show();
//当你用一个基类指针或引用指向一个继承类对象的时候,
//调用一个虚函数时, 实际调用的是继承类的版本。
private:
std::string name;
};
Person::Person(std::string name)
{
this->name = name;
}
void Person::Show(){
//父类的函数
  cout << "ZhuangShiDe"<< name << endl;
}
//装饰类
//负责穿戴不同的服装 有一个参数是服装对象
class Finery :public Person{
protected:
Person* component;
public:
Finery(){}
void Decorator(Person* component);//穿衣服函数
void Show();
};
void Finery::Decorator(Person* component){
this->component = component;
}
void Finery::Show(){
//子类的函数
if (component != NULL)
component->Show();
}
//具体服装
class Tshirts :public Finery{
public:
Tshirts(){}
void Show(){
std::cout << "T shirts";
Finery::Show();
}
};
class Sneakers :public Finery{
public:
Sneakers(){}
void Show(){
std::cout << " Sneakers";
Finery::Show();
}
};
int main(){
Person* xc = new Person("XiaoCai");
std::cout << "first style:" << std::endl;
Tshirts* ts = new Tshirts();
Sneakers* sn = new Sneakers();
ts->Decorator(xc);//小菜穿第一件衣服
sn->Decorator(ts);//小菜穿第二件衣服
sn->Show();
return 0;
}

输出结果:
first style:
SneakersT shirtsZhuangShiDeXiaoCai

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值