看到了大话设计模式的第6章——装饰模式,记录一下,加深印象
装饰模式(Decorator):动态地给一个对象增加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
将上面的UML图转化成C++代码,如下:
/*
* initm.com
* 作者:Stupid
* 时间:2017-10-18 23:06
* 描述: 代码使用QT5.9+MinGW53_32编译通过,代码为装饰模式的基本结构代码。
*/
#include <iostream>
class Component
{
public:
virtual void Operation() = 0;
};
class ConcreteComponent: public Component
{
public:
virtual void Operation() override final{
std::cout << "\tConcreteComponent execute" << std::endl;
}
};
class Decorator: public Component
{
protected:
Component* m_pComponent;
public:
Decorator(Component* pComponent): m_pComponent(pComponent){}
virtual void Operation() override{
m_pComponent->Operation();
}
};
class ConcreteDecoratorA: public Decorator
{
public:
ConcreteDecoratorA(Component* pComponent):Decorator(pComponent){;}
void Operation() override final{
m_pComponent->Operation();
std::cout << "\tConcreteDecoratorA" << std::endl;
}
};
class ConcreteDecoratorB: public Decorator
{
public:
ConcreteDecoratorB(Component* pComponent):Decorator(pComponent){;}
void Operation() override final{
m_pComponent->Operation();
std::cout << "\tConcreteDecoratorB" << std::endl;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//新建一个原始的对象
std::cout << "1--------------------------------------" << std::endl;
ConcreteComponent* pConcreteComponent = new ConcreteComponent;
pConcreteComponent->Operation();
//然后加上一层的装饰
std::cout << "2--------------------------------------" << std::endl;
ConcreteDecoratorA* pConcreteDecoratorA = new ConcreteDecoratorA(pConcreteComponent);
pConcreteDecoratorA->Operation();
//加上第二层的装饰
std::cout << "3--------------------------------------" << std::endl;
ConcreteDecoratorB* pConcreteDecoratorB = new ConcreteDecoratorB(pConcreteDecoratorA);
pConcreteDecoratorB->Operation();
return a.exec();
}
大致代码就是上面的样子,如果有差错欢迎大家在下面留言指正。
大致说一下,其实装饰模式的名字就已经很形象地说明了它的用途,就是可以在原有功能的基础上再添加上一些东西,原来的东西是不需要动的。
书中的例子很形象,就像人们穿衣服(一个人里面穿一件秋裤,外面可以再穿一条牛仔裤)