装饰者模式动态地给对象添加新职责,装饰者提供了比继承更有弹性的替代方案
适用场景:
(1)需要扩展一个类的功能,或给一个类增加附加责任。
(2)需要动态地给一个对象增加功能,这些功能可以再动态地撤销。
(3)需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。
优点:
(1)Decorator模式与继承关系的目的都是要扩展对象的功能,但是Decorator可以提供比继承更多的灵活性。
(2)通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。
#include <iostream>
#include <string>
using namespace std;
class Phone
{
public:
virtual ~Phone() { }
virtual void decoratePhone() = 0;
};
class Iphone : public Phone
{
public:
Iphone(string name) : m_name(name) {}
void decoratePhone() { cout << "decorate " << m_name << endl; }
private:
string m_name;
};
class Mi : public Phone
{
public:
Mi(string name) : m_name(name) {}
void decoratePhone() { cout << "decorate " << m_name << endl; }
private:
string m_name;
};
class DecoratorPhone : public Phone
{
public:
DecoratorPhone(Phone *phone) : m_phone(phone) {}
void decoratePhone() { m_phone->decoratePhone(); }
private:
Phone *m_phone;
};
class DecorateScreen : public DecoratorPhone
{
public:
DecorateScreen(Phone *phone) : DecoratorPhone(phone) {}
void decoratePhone()
{
DecoratorPhone::decoratePhone();
enlargeScreen();
}
private:
void enlargeScreen() { cout << "enlarge screen" << endl; }
};
class DecorateCraft : public DecoratorPhone
{
public:
DecorateCraft(Phone *phone) : DecoratorPhone(phone) {}
void decoratePhone()
{
DecoratorPhone::decoratePhone();
enhanceCraft();
}
private:
void enhanceCraft() { cout << "enhance craft" << endl; }
};
int main()
{
Iphone iphone("Iphone 6");
Mi mi("MI 3s");
DecorateScreen ds(&iphone);
ds.decoratePhone();
DecorateCraft dc(&mi);
dc.decoratePhone();
return 0;
}