#pragma once

#ifndef DECORATOR_H

#define DECORATOR_H

// 抽象基类,定义一个对象接口,可以为这个接口动态的添加职责.
class Component
{
public:
Component(){}
virtual ~Component(){}

// 纯虚函数,由派生类实现
virtual void Operation() = 0;
};

// 抽象基类,维护一个指向Component对象的指针
class Decorator : public Component
{
public:
Decorator(Component* pComponent)
: m_pComponent(pComponent){}
virtual ~Decorator();

protected:
Component* m_pComponent;
};

// 派生自Component,在这里表示需要给它动态添加职责的类
class ConcreateComponent : public Component
{
public:
ConcreateComponent(){}
virtual ~ConcreateComponent(){}
virtual void Operation();
};

// 派生自Decorator,这里代表为ConcreateComponent动态添加职责的类
class ConcreateDecorator : public Decorator
{
public:
ConcreateDecorator(Component* pComponent)
: Decorator(pComponent){}
virtual ~ConcreateDecorator(){}
virtual void Operation();

private:
void AddedBehavior();
};

#endif


#include "StdAfx.h"
#include "decorator_impl.h"

#include <iostream>

Decorator::~Decorator()
{
delete m_pComponent;
m_pComponent = NULL;
}

void ConcreateComponent::Operation()
{
std::cout << "Operation of ConcreateComponent\n";
}

void ConcreateDecorator::Operation()
{
m_pComponent->Operation(); //componet原有职责
AddedBehavior(); //decorator动态添加职责
}

void ConcreateDecorator::AddedBehavior()
{
std::cout << "AddedBehavior of ConcreateDecorator\n";
}


// Decorator.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>

#include "decorator_impl.h"

using namespace std;
//动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活
int _tmain(int argc, _TCHAR* argv[])
{
// 初始化一个Component对象
Component* pComponent = new ConcreateComponent();
// 采用这个Component对象去初始化一个Decorator对象,
cout<<"before decorator"<<endl;
pComponent->Operation();
cout<<endl;
// 这样就可以为这个Component 对象动态添加职责
Decorator* pDecorator = new ConcreateDecorator(pComponent);
//Component* pDecorator = new ConcreateDecorator(pComponent);
cout<<"after decorator"<<endl;
//对外表现为执行了component基本职责,并执行了decorator动态添加的职责
pDecorator->Operation();

delete pDecorator;
system("pause");

return 0;
}