装饰者模式
来源:互联网 发布:水利设计软件 编辑:程序博客网 时间:2024/05/16 16:21
装饰者模式:动态的讲责任附加到对象。若要扩展功能,装饰者提供了比继承更有弹性的替代方案;
关键:装饰者和被装饰着必须是一样的类型,即有共同的超类;利用继承达到类型匹配,而不是获得行为;
原则:对扩展开放,对修改关闭;
缺点:装饰者会导致设计中出现许多小对象,如果过度使用,会让程序变得很复杂;
书中类图框架:
装饰方式:
部分代码:
//装饰者模式#include <iostream>using namespace std;#include <string>class Beverage{string description;public:Beverage():description("Unknown Beverage"){};void set_decrp( const string& str ){description = str;}virtual string getdescription(){return description;}virtual double cost(){return 0.0;}};class Espresso:public Beverage{public:Espresso(){set_decrp( "Espresso");}double cost(){return 1.99;}};class HouseBlend:public Beverage{public:HouseBlend(){set_decrp( "House Blend Coffee");}double cost(){return 0.89;}};class CondimentDecrator:public Beverage{public:virtual string getdescription(){return Beverage::getdescription();}};class Mocha:public CondimentDecrator{Beverage *beverage;public:Mocha(Beverage *beverage){this->beverage = beverage;}string getdescription(){return beverage->getdescription() + " , Mocha";}double cost(){return 0.20 + beverage->cost();}};class Soy:public CondimentDecrator{Beverage *beverage;public:Soy(Beverage *beverage){this->beverage = beverage;}string getdescription(){return beverage->getdescription() + " , Soy";}double cost(){return 0.15 + beverage->cost();}};class Whip:public CondimentDecrator{Beverage *beverage;public:Whip(Beverage *beverage){this->beverage = beverage;}string getdescription(){return beverage->getdescription() + " , Whip";}double cost(){return 0.10 + beverage->cost();}};void test(){Beverage *beverage = new Espresso();beverage = new Mocha( beverage );beverage = new Mocha( beverage );beverage = new Whip( beverage );cout<<beverage->getdescription()<<" $"<<beverage->cost()<<endl;}int main(){<span style="white-space:pre"></span>test();<span style="white-space:pre"></span>return 0;}/**/
0 0
- 装饰者模式(Derector)
- 装饰者模式
- Decorator 装饰者模式
- 装饰者设计模式
- 装饰者模式
- 装饰者模式
- 装饰者模式
- 装饰者模式(Decorator)
- 装饰者模式
- 装饰者模式
- 装饰者模式
- 装饰者模式 DecoratorPattern
- 设计模式 - 装饰者
- 装饰者模式
- 装饰者模式
- 装饰者模式 - 2
- 装饰者模式
- 装饰者模式
- 银联(客商宝)无卡头手机pos机 全国火热招商中!0后期!低门槛!
- Grep linux文本搜索
- 使用Spring for Android改善数据交互流程
- Log4net测试笔记
- iOS中代码支持多国语言切换的实现(Xcode5+iOS7)
- 装饰者模式
- 一款模拟养成类游戏的策划大纲
- Java IO流笔记1
- USACO Section 1.5 Prime Palindromes
- Port Forwarding & Port Triggering
- 王立平--svn服务器搭建
- 设计模式——单例模式(Singleton)
- 虚拟主机,你那些不知道的事
- hdu 5023 A Corrupt Mayor's Performance Art 2014 ACM/ICPC Asia Regional Guangzhou Online