设计模式初探3——装饰者模式(Decorator Pattern)

装饰者模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。


适用范围:

1. 需要扩展一个类的功能,或给一个类添加附加职责。
2. 需要动态的给一个对象添加功能,这些功能可以再动态的撤销。
3. 需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变的不现实。
4. 当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。

UML图:


测试代码:
我们创建一个Toy抽象类,然后来生产不同的玩具,并为它加上各种功能。
#include <iostream>
#include <string>
using namespace std;

class Toy {
public:
    virtual string getDescription() = 0;
};

我们先生产一个玩具鸭,它还不太像一只鸭子,并且不能发声:
class Duck : public Toy {
public:
    string getDescription(){ return "I'm a simple Toy-Duck. "; }
}; 

接着是装饰类的基类,它包含Toy基类的指针,以便访问到我们的玩具鸭:
class Decorator : public Toy {
public:
    Decorator(Toy* t) : toy(t){}
protected:
    Toy* toy;
};

创建形状装饰者和发声装饰者:
class ShapeDecorator : public Decorator {
public:
    ShapeDecorator(Toy* t) : Decorator(t){}
    string getDescription() {
        return toy->getDescription.append("Now I have new shape. ");
    }
};

class SoundDecorator : public Decorator {
public:
    SoundDecorator(Toy* t) : Decorator(t){}
    string getDescription() {
        return toy->getDescription.append("Now I can quack. ");
    }
};

好了,我们在main函数中测试一下:
int main()    
{    
    Toy *toy = new Duck();
    cout << toy->getDescription();

    toy = new ShapeDecorator(toy);
    cout << toy->getDescription();
    
    toy = new SoundDecorator(toy);
    cout << toy->getDescription();   
    return 0;    
} 

让我们再关注一条十分重要的设计原则:
对扩展开放,对修改关闭。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值