转载自:装饰器模式(Decorator) C++
对原文章的代码有所修改,并增加了一些内容。
装饰器模式是比较常用的一种设计模式,Python中就内置了对于装饰器的支持。
具体来说,装饰器模式是用来给对象增加某些特性或者对被装饰对象进行某些修改。
如上图所示,需要被装饰的对象在最上方,它自身可以有自己的实例,一般通过抽象类来实现(Java中也可以通过接口实现)。
右侧中间是一个装饰器类或者接口,其实内容与原对象基本一致,不过我们自定义的装饰器一般会继承这个装饰器基类。
最下层就是具体的装饰器了,可以看到,具体装饰器类中需要包含被装饰对象成员(也就是说,装饰器需要和被装饰对象有同样的子类),然后增加一些额外的操作。
下面的代码是一个买煎饼的例子,如我们生活中所见,可以选基础煎饼(鸡蛋煎饼,肉煎饼等),然后再额外加别的东西:
#include <iostream>
#include <string>
using namespace std;
class Pancake //基类 抽象类
{
public:
string description = "Basic Pancake";
virtual string getDescription() {
return description;
}
virtual double cost() = 0;
public:
Pancake(){}
virtual ~Pancake(){}
};
class CondimentDecorator : public Pancake //装饰器
{
public:
Pancake* pancake;
public:
CondimentDecorator(Pancake* pcake) : pancake(pcake) {
//...
}
virtual ~CondimentDecorator() {
//...
}
};
class EggPancake : public Pancake //鸡蛋煎饼
{
public:
EggPancake() {
description = "EggPancake";
}
~EggPancake(){}
double cost() {
return 5;
}
};
class MeatPancake : public Pancake //肉煎饼
{
public:
MeatPancake() {
description = "MeatPancake";
}
~MeatPancake(){}
double cost() {
return 6;
}
};
class PotatoEx : public CondimentDecorator //额外加土豆
{
public:
PotatoEx(Pancake* pancake) : CondimentDecorator(pancake) {
//...
}
~PotatoEx(){}
string getDescription() {
return this->pancake->getDescription() + ", Potato";
}
double cost() {
return this->pancake->cost() + 1;
}
};
class BaconEx : public CondimentDecorator //额外加培根
{
public:
BaconEx(Pancake* pancake) : CondimentDecorator(pancake) {
//...
}
~BaconEx(){}
string getDescription() {
return this->pancake->getDescription() + ", Bacon";
}
double cost() {
return this->pancake->cost() + 2;
}
};
int main()
{
Pancake* pan = new EggPancake();
PotatoEx* po = new PotatoEx(pan);
BaconEx* ba = new BaconEx(po);
cout << ba->getDescription() << " $ : " << ba->cost() << endl;
return 0;
}
运行结果:
可以看到,Pancake是煎饼的基类,这个基类因为定义了纯虚函数cost,所以不能被实例化。同样,装饰器基类CondimentDecorator也不能被实例化。
后面,EggPancake和MeatPancake是Pancake的派生类,是实际存在的类。
BaconEx和PotatoEx就是我们定义的装饰器对象,其中包含了Pancake的指针,可以对Pancake及其派生类进行操作。
装饰器模式的优点:
1、可以轻松对已存在的对象进行修改和包装,在被装饰者的前面或者后面添加自己的行为,而无需修改原对象。
2、可以动态、不限量地进行装饰,可以更灵活地扩展功能。
相对地,装饰器模式有很明显的缺点:
1、会加入大量的小类,即使只添加一个功能,也要额外创建一个类,使得程序更复杂。
2、增加代码复杂度,使用装饰器模式不但需要实例化组件,还要把组件包装到装饰者中。