// 2_Decorator.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
/**
* 装饰模式(Decorator): 动态地给一个对象添加一些额外的职责, 就增加
* 功能来说, 装饰模式比生成子类更为灵活
**/
class Component
{
public:
virtual void Operation() {};
};
class ConcreteComponent: public Component
{
public:
void Operation() override { cout << "具体对象的操作: " << endl; }
};
class Decorator : public Component
{
protected:
Component* _component;
public:
void SetComponent(Component* comp) { _component = comp; }
public:
void Operation() override
{
if (_component != nullptr)
{
_component->Operation();
}
}
};
class ConcreateDecoratorA : public Decorator
{
public:
void Operation() override
{
Decorator::Operation();
cout << "具体装饰对象A的操作" << endl;
}
};
class ConcreateDecoratorB : public Decorator
{
public:
void Operation() override
{
Decorator::Operation();
cout << "具体装饰对象B的操作" << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Component* pCom = new ConcreteComponent();
ConcreateDecoratorA *dA = new ConcreateDecoratorA();
ConcreateDecoratorB *dB = new ConcreateDecoratorB();
dA->SetComponent(pCom);
dB->SetComponent(dA);
dB->Operation();
return 0;
}
运行结果