设计模式:装饰模式
2016-02-01 13:45
363 查看
装饰模式:
1 动态地给一个对象添加一些额外的功能。
2 给对象添加功能,可以直接修改类,添加相应的功能;也可以派生对应的子类来扩展;又可以使用组合,我们应该尽量使用对象组合。
3 定义一个简单的类,并且用装饰类给它逐渐地添加功能,从简单的部件组合出复杂的功能。
例如给一个电脑装屏幕保护、键盘保护:
1 动态地给一个对象添加一些额外的功能。
2 给对象添加功能,可以直接修改类,添加相应的功能;也可以派生对应的子类来扩展;又可以使用组合,我们应该尽量使用对象组合。
3 定义一个简单的类,并且用装饰类给它逐渐地添加功能,从简单的部件组合出复杂的功能。
例如给一个电脑装屏幕保护、键盘保护:
#include<iostream> using namespace std; //抽象电脑类 class Computer{ public: virtual ~Computer(){} virtual void show(){}; }; //具体电脑类 class LenovoComputer:public Computer{ public: void show(){ cout<<"LenovoComputer"<<endl; } }; //装饰电脑类 class DecoratorComputer:public Computer{ public: DecoratorComputer(Computer* computer){ mComputer=computer; } virtual void show(){ mComputer->show(); } private: Computer* mComputer; }; //具体装饰电脑类 class ScreenProtectorComputer:public DecoratorComputer{ public: ScreenProtectorComputer(Computer* computer):DecoratorComputer(computer){} void show(){ DecoratorComputer::show(); add(); } void add(){ cout<<"Add ScreenProtector"<<endl; } }; //具体装饰电脑类 class KeyboardProtectorComputer:public DecoratorComputer{ public: KeyboardProtectorComputer(Computer* computer):DecoratorComputer(computer){} void show(){ DecoratorComputer::show(); add(); } void add(){ cout<<"Add KeyboardProtector"<<endl; } }; int main(){ Computer* LenovoY470=new LenovoComputer; //加屏幕保护膜 DecoratorComputer* aScreenProtectorComputer=new ScreenProtectorComputer(LenovoY470); aScreenProtectorComputer->show(); cout<<"-------------------------"<<endl; //再加键盘保护膜 DecoratorComputer* aKeyboardProtectorComputer=new KeyboardProtectorComputer(aScreenProtectorComputer); aKeyboardProtectorComputer->show(); delete LenovoY470; LenovoY470=NULL; delete aScreenProtectorComputer; aScreenProtectorComputer=NULL; delete aKeyboardProtectorComputer; aKeyboardProtectorComputer=NULL; return 0; }
相关文章推荐
- 关于AndroidManifest.xml中的android:debuggable
- 北京移动流量超市
- 程序猿怎样解除烦恼
- 极客DIY:用树莓派制作低成本高清监控摄像机
- Linux Redis
- 前台js分页,自己手写逻辑
- Android 常见面试 知识点小结
- 如何使用Spark大规模并行构建索引
- 7.4 Models -- Pushing Records into the Store
- 支付宝 return_url 和 notify_url 的区分
- 递归自举其它
- STL:二分法模板
- LeetCode 240. Search a 2D Matrix II
- 【爱江山越野跑】ITRA积分认证流程
- sqlserver - FOR XML PATH
- iOS中的UIKIT_EXTERN
- Android AES加密/解密代码
- HDU1863 并查集与最小生成树
- Mgengto 导入所有产品的图片,按sku命名分类
- 推荐一个不错的bootstrap学习网站