(三)装饰模式
2015-09-15 18:08
204 查看
见注释:
输出:
Coffee Constructor...
Coffee Constructor...
Decorator Constructor...
AddMilk Constructor...
Coffee Constructor...
Decorator Constructor...
AddSuger Constructor...
5
Size :16
AddSuger DisConstructor...
Decorator DisConstructor...
AddMilk DisConstructor...
Decorator DisConstructor...
Coffee DisConstructor...
Coffee DisConstructor...
Coffee DisConstructor...
请按任意键继续. . .
// test.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <string> #include <iostream> #include <memory>//为了应用智能指针 using namespace std; //装饰模式,动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。 //装饰模式是为已有功能动态添加更多功能的一种方式。 //当系统需要新功能时,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责 //或主要行为。 //? //他把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此当需要执行特殊行为时, // 客户端代码就可以再运行时根据需要有选择的、按顺序的使用装饰功能包装的对象了。 // 有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。 class Coffee { public: Coffee() : m_price(1.0) { cout << "Coffee Constructor..." << endl; } virtual ~Coffee() { cout << "Coffee DisConstructor..." << endl; } //咖啡有计算价格方法 virtual double cost() { return m_price; } private: double m_price; }; class Decorator : public Coffee { public: Decorator() { cout << "Decorator Constructor..." << endl; } virtual ~Decorator() { cout << "Decorator DisConstructor..." << endl; } public: shared_ptr<Coffee> m_f;//一个具体的咖啡对象 }; //加牛奶装饰类 class AddMilk : public Decorator { public: ~AddMilk() { cout << "AddMilk DisConstructor..." << endl; } //咖啡类型的对象进行装饰 AddMilk(shared_ptr<Coffee> f) { cout << "AddMilk Constructor..." << endl; m_f = f; } //加牛奶的价格计算方式 double cost() { return 2.5 + m_f->cost(); } }; //加糖装饰类 class AddSuger : public Decorator { public: ~AddSuger() { cout << "AddSuger DisConstructor..." << endl; } //咖啡类型的对象进行装饰 AddSuger(shared_ptr<Coffee> f) { cout << "AddSuger Constructor..." << endl; m_f = f; } //加糖的价格计算方式 double cost() { return 1.5 + m_f->cost(); } }; int _tmain(int argc, _TCHAR* argv[]) { //对原味咖啡对象进行装饰,先加牛奶后加糖 shared_ptr<Coffee> coffee(new AddSuger(shared_ptr<Coffee>(new AddMilk(shared_ptr<Coffee>(new Coffee()))))); //这样咖啡的价格就被附加。 cout << coffee->cost() << endl; //计算下集成体系下的内存大小 cout << "Size :" << sizeof(*coffee) << endl; return 0; }
输出:
Coffee Constructor...
Coffee Constructor...
Decorator Constructor...
AddMilk Constructor...
Coffee Constructor...
Decorator Constructor...
AddSuger Constructor...
5
Size :16
AddSuger DisConstructor...
Decorator DisConstructor...
AddMilk DisConstructor...
Decorator DisConstructor...
Coffee DisConstructor...
Coffee DisConstructor...
Coffee DisConstructor...
请按任意键继续. . .
相关文章推荐
- mysql主从复制
- 使用elasticsearch作为TSDB
- Notes on Convolutional Neural Networks(阅读)
- 关于冒烟测试、随机测试、猴子测试
- as3 字符串 根据分隔符分隔数据
- 关于空白模板插件的使用
- nc 命令
- javascript函数科里化
- Bitmap裁剪图片
- UIday1601:网络编程 GET POST 的同步或异步请求,服务器接口的简单介绍。
- nginx命令详解
- 数据库设计学习博客文章汇总
- 国内yum源
- Nginx 的 proxy_store 缓存
- jQuery 实现侧边浮动导航菜单效果
- 让apache支持https的设置步骤
- UDP协议基础知识
- 读取文件内容的一般方式
- top命令使用详解
- Activity四种启动方式