设计模式学习-Decorator装饰者模式
来源:互联网 发布:图片相似对比软件 编辑:程序博客网 时间:2024/06/15 09:27
装饰模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
Beverage 饮料
Espresso 浓咖啡
CondimentDecorator 配料,继承于Beverage类
Mocha 摩卡
Whip 奶泡
代码:
#include<iostream>#include<string>#include<vector>using namespace std;//饮料class Beverage{public:Beverage(){}virtual string getdescription() = 0;virtual double cost() = 0;string name;};class Espresso : public Beverage{public:Espresso(){name = "Espresso";}double cost(){return 2.0;}string getdescription(){return name;}};//配料class CondimentDecorator : public Beverage{public:Beverage* beverage;};//摩卡class Mocha : public CondimentDecorator{public:Mocha(Beverage* _beverage){beverage = _beverage;name = "Mocha";}double cost(){return beverage->cost() + 1.5;}string getdescription(){return beverage->getdescription() + "," + name;}};//奶泡class Whip : public CondimentDecorator{public:Whip(Beverage* _beverage){beverage = _beverage;name = "Whip";}double cost(){return beverage->cost() + 0.9;}string getdescription(){return beverage->getdescription() + "," + name;}};int main(){cout << "原味咖啡" << endl;Beverage* p1 = new Espresso();cout << p1->getdescription() << endl;cout << "价格: " << p1->cost() <<endl;Beverage* p2 = new Mocha(p1);cout << p2->getdescription() << endl;cout << "价格: " << p2->cost() <<endl;Beverage* p3 = new Whip(p2);cout << p3->getdescription() << endl;cout << "价格: " << p3->cost() <<endl;delete p3;delete p2;delete p1;getchar();return 0;}将调料作为装饰类,可根据需要对饮料添加相应的调料。
0 0
- 设计模式学习-Decorator装饰者模式
- 设计模式学习-Decorator(装饰)
- Decorator装饰者设计模式
- 设计模式入门学习 Decorator装饰模式
- 设计模式学习笔记--装饰(Decorator)模式
- [设计模式学习笔记]DECORATOR装饰模式
- 设计模式学习笔记十(Decorator装饰者模式)
- 设计模式学习--装饰者模式(Decorator Pattern)
- 【设计模式】学习笔记3:装饰者模式(Decorator )
- 设计模式学习(五) -- 装饰者模式 Decorator Pattern
- 设计模式学习--装饰者模式(Decorator Pattern)
- 设计模式学习笔记--装饰者模式(Decorator Pattern)
- 设计模式学习总结:装饰者模式(Decorator Pattern)
- Java设计模式学习—装饰者模式(Decorator)
- 设计模式 - 装饰 Decorator
- Decorator(装饰)设计模式
- 设计模式之Decorator(装饰者模式)
- 设计模式-装饰者模式(Decorator Pattern)
- 【USACO1.1_3】★Friday the Thirteenth 黑色星期五
- 开通博客
- C++中的struct和class的区别
- 如何学习Oracle-eygle的方法经验谈
- Catalan数(一)
- 设计模式学习-Decorator装饰者模式
- static控件透明
- -----------串口的结构体---termios 的属性介绍
- 让VC编译的程序链接到系统的 msvcrt.dll 的方法
- 抢食!传google将依托自有光纤推无线网络效劳
- HDU 1711 Number Sequence(KMP:找模板第一次出现的位置)
- android 修改桌面图标大小
- UVA 639 - Don't Get Rooked 暴力回溯
- 设计模式之观察者模式