适用情境:给一个类添加一些额外的功能,而不修改原来类的代码.添加的功能一般不是非常重要的核心功能,而是较少使用的次要功能.添加的功能放在一个单独的类中,客户端可以对添加的功能进行选择.
优点:新添加的功能不影响被装饰类的功能,不增加被装饰类的复杂度.
缺点:需要修改客户端代码.
// component.h
#ifndef COMPONENT_H
#define COMPONENT_H
class Component
{
public:
Component();
virtual void Operation() = 0;
};
#endif // COMPONENT_H
// component.cpp
#include "component.h"
Component::Component()
{
}
// concretecomponent.h
#ifndef CONCRETECOMPONENT_H
#define CONCRETECOMPONENT_H
#include "component.h"
class ConcreteComponent : public Component
{
public:
ConcreteComponent();
virtual void Operation();
};
#endif // CONCRETECOMPONENT_H
// concretecomponent.cpp
#include <iostream>
#include "concretecomponent.h"
ConcreteComponent::ConcreteComponent()
{}
void ConcreteComponent::Operation()
{
std::cout << "ConcreteCompoent::operation()" << std::endl;
}
// decorator.h
#ifndef DECORATOR_H
#define DECORATOR_H
#include "component.h"
class Decorator : public Component
{
public:
Decorator(Component *tmp);
virtual void Operation();
public:
Component *m_component;
};
#endif // DECORATOR_H
// decorator.cpp
#include "decorator.h"
Decorator::Decorator(Component *tmp)
{
m_component = tmp;
}
void Decorator::Operation()
{
m_component->Operation();
}
// concretedecorator.h
#ifndef CONCRETEDECORATOR_H
#define CONCRETEDECORATOR_H
#include "decorator.h"
class ConcreteDecorator : public Decorator
{
public:
ConcreteDecorator(Component *tmp);
virtual void Operation();
virtual void NewOperation();
};
#endif // CONCRETEDECORATOR_H
// concretedecorator.cpp
#include <iostream>
#include "concretedecorator.h"
ConcreteDecorator::ConcreteDecorator(Component *tmp) : Decorator(tmp)
{
}
void ConcreteDecorator::Operation()
{
m_component->Operation();
NewOperation();
}
void ConcreteDecorator::NewOperation()
{
std::cout << "ConcreteDecorator::NewOperation()" << std::endl;
}
客户端:
// main.cpp
#include <iostream>
#include "component.h"
#include "decorator.h"
#include "concretedecorator.h"
#include "concretecomponent.h"
using namespace std;
int main(int argc, char *argv[])
{
Component *component = new ConcreteComponent();
Component *component1 = new ConcreteDecorator(component);
component1->Operation();
return 0;
}