c++设计模式-装饰器模式(1.装饰类继承被装饰类;2.装饰类将被装饰类作为自己的属性;3.装饰类与被装饰类有共同父类)

using namespace std;
//装饰器模式(分三种:
// 1.装饰类继承被装饰类
// 2.装饰类将被装饰类作为自己的属性
// 3.装饰类与被装饰类有共同父类**
//1.装饰类继承被装饰类
class Person {
protected:
string m_name;
public:
Person(string name) :m_name(name) {}
virtual void show() = 0;
};
class Man :public Person {
public:
Man(string name) :Person(name) {}
virtual void show() {
cout << “男孩” << m_name;
}
};
class ExtendDecorative:public Person {
public:
ExtendDecorative(string name):Person(name) {}
virtual void addClothes() {
cout << m_name << “穿上了衣服” << endl;
}
virtual void necklacing() {
cout << m_name << “戴上了项链” << endl;
}
virtual void show() {
addClothes();
necklacing();
}
};
void testExtendDecorative() {
shared_ptr<ExtendDecorative> extendDecorative{new ExtendDecorative(“huahua”) };
extendDecorative->show();
}
//2.装饰类将被装饰类作为自己的属性
class Car {
public:
virtual void show() = 0;
};
class Audi :public Car {
void show() {
cout << “这是一辆奥迪车”;
}
};
//装饰层
class Decorative{
protected:
shared_ptr<Car> m_car;
public:
Decorative(shared_ptr<Car> car):m_car(car){}
void show() {
m_car->show();
//加装饰
cout << “,可以弹射漂移” << endl;
}
};
//测试被装饰类作为属性
void testDecorative() {
shared_ptr<Car>car{ new Audi() };
shared_ptr<Decorative> decorative{ new Decorative(car) };
decorative->show();
}
//3.装饰类与被装饰类有共同父类(现在给的例子两个子类没有任何联系)
class Transfer {
public:
virtual void answer() = 0;
virtual void sweep() {}
virtual void TakeOutTheGarbage() {}
};
//被装饰类
class Robot :public Transfer {
public:
virtual void answer() {
cout << “Robot回答问题” << endl;
}
virtual void sweep() {
cout << “扫地” << endl;
}
};
//装饰类
class CommonParentDecorative :public Transfer {
private:
shared_ptr<Transfer>m_transfer;
public:
CommonParentDecorative(shared_ptr<Transfer> transfer):m_transfer(transfer) {}
virtual void answer() {
cout << “CommonParentDecorative回答问题” << endl;
}
virtual void TakeOutTheGarbage() {
cout << “CommonParentDecorative倒垃圾” << endl;
}
};
//测试装饰类与被装饰类有共同父类
void testCommonParentDecorative() {
shared_ptr<Transfer>transfer{ new Robot };
transfer->answer();
transfer->sweep();
shared_ptr<Transfer>transfer1{ new CommonParentDecorative(transfer) };
transfer1->answer();
transfer1->TakeOutTheGarbage();
}
int main() {
//1.测试装饰类继承被装饰类
/testExtendDecorative();/
//2.装饰类将被装饰类作为自己的属性
testDecorative();
//3.测试装饰类与被装饰类有共同父类
/testCommonParentDecorative();/
return 0;
}
不好意思,脑子里想不到例子了,望谅解,大家凑合看看,谢谢

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值