C++设计模式之装饰模式

2020-01-06 12:53:34王旭

UML类图

C++设计模式之装饰模式

Component:定义一个对象接口,可以给这些对象动态地添加职责;

ConcreteComponent:定义一个具体的Component,继承自ConcreateComponent,重写了Component类的虚函数;

Decorator:维持一个指向Component对象的指针,该指针指向需要被装饰的对象;并定义一个与Component接口一致的接口;

ConcreteDecorator:向组件添加职责。

代码实现:

 

复制代码
/*
** FileName     : DecoratorPatternDemo
** Author       : Jelly Young
** Date         : 2013/12/19
** Description  : More information, please go to http://www.easck.com/> */
#include <iostream>
using namespace std;
class Component
{
public:
     virtual void Operation() = 0;
};
class ConcreteComponent : public Component
{
public:
     void Operation()
     {
          cout<<"I am no decoratored ConcreteComponent"<<endl;
     }
};
class Decorator : public Component
{
public:
     Decorator(Component *pComponent) : m_pComponentObj(pComponent) {}
     void Operation()
     {
          if (m_pComponentObj != NULL)
          {
               m_pComponentObj->Operation();
          }
     }
protected:
     Component *m_pComponentObj;
};
class ConcreteDecoratorA : public Decorator
{
public:
     ConcreteDecoratorA(Component *pDecorator) : Decorator(pDecorator){}
     void Operation()
     {
          AddedBehavior();
          Decorator::Operation();