为一个类添加新功能,适配器的好处添加的新功能适用于所有该类型的类
decorator.h
#ifndef _DECORATOR_H
#define _DECORATOR_H
#include <iostream>
using namespace std;
class Component
{
public:
virtual ~Component() {}
virtual void Operation() {};
protected:
Component() {};
};
class ConcreateComponent : public Component
{
public:
~ConcreateComponent() {};
void Operation() {
cout << "ConcreateComponent" << endl;
}
};
class Decorator : public Component
{
public:
Decorator(Component* com) {
_com = com;
}
virtual ~Decorator() {};
void Operation() {
cout << "Decorator" << endl;
}
protected:
Component* _com;
};
class ConcreateDecorator : public Decorator
{
public:
ConcreateDecorator(Component* com) : Decorator(com) {};
~ConcreateDecorator() {};
void Operation() {
_com->Operation();
AddBehavior();
}
void AddBehavior() {
cout << "AddBehavior" << endl;
}
};
#endif // _DECORATOR_H
decorator.cpp
#include "decorator.h"
int main()
{
Component* com = new ConcreateComponent;
Decorator* dec = new ConcreateDecorator(com);
dec->Operation();
return 0;
}
编译:make decorator