声明:本博文篇幅短,适合review。
一、概念
装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
二、结构模式图
三、例子
class Person
{
public:
Person();
~Person();
virtual void show()
{
std::cout<<" show clothes"<<endl;
}
};
class Clothes : public Person
{
public:
Clothes(Person * _component)
{
m_component = _component;
}
~Clothes();
protected:
Person * m_component;
public:
void show() override {}
};
class TShirt : public Clothes
{
public:
TShirt(Person * _component) : Clothes(_component)
{
}
~TShirt();
void show() override
{
std::cout<<" show T-Shirt"<<endl;
m_component->show();
}
};
class Jeans : public Clothes
{
public:
Jeans(Person * _component) : Clothes(_component)
{
}
~Jeans();
void show() override
{
std::cout<<" show Jeans"<<endl;
m_component->show();
}
};
void main()
{
Person * ps = new Person();
Clothes * cts = new TShirt(ps);
cts->show();
Clothes * js = new Jeans(cts);
js->show();
}
四、优缺点
1、优点
a、Decorator模式与继承关系的目的都是要扩展对象的功能,但是Decorator可以提供比继承更多的灵活性。
b、通过使用不同的具体装饰类以及这些装饰类的排列组合,可以创造出很多不同行为的组合。
c、遵守大部分GRASP原则和常用设计原则,高内聚、低偶合。
2、缺点
a、这种比继承更加灵活机动的特性,也同时意味着更加多的复杂性。
b、装饰链不能过长,否则会影响效率。
c、因为所有对象都是继承于Component,所以如果Component内部结构发生改变,则不可避免地影响所有子类(装饰者和被装饰者)。