装饰(Decorator)模式又名包装(Wrapper)模式[GOF95]。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。
装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰模式可以在不使用创造更多子类的情况下,将对象的功能加以扩展。
在装饰模式中的各个角色有:
- 抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
- 具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
- 装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。
- 具体装饰(Concrete Decorator)角色:负责给构件对象"贴上"附加的责任。
UML结构图:
实现如下
#ifndef DECORATOR_H_
#define DECORATOR_H_
#include "stdafx.h"
class Component
{
public:
Component(){}
virtual~ Component(){}
virtual void Operation() = 0;
};
class Decorator : public Component
{
public:
Decorator(Component* apComponent) : m_pComponent(apComponent){}
virtual~Decorator();
virtual void Operation();
protected:
Component* m_pComponent;
};
class ConcreateDecorator : public Decorator
{
public:
ConcreateDecorator(Component* apComponent) : Decorator(apComponent){}
virtual~ ConcreateDecorator(){}
virtual void Operation();
private:
virtual void AddedBehavior();
};
class ConcreateComponent : public Component
{
public:
virtual void Operation();
};
#endif
#include "stdafx.h"
#include "Decorator.h"
#include <iostream>
using namespace std;
Decorator::~Decorator()
{
delete m_pComponent;
m_pComponent = NULL;
}
void Decorator::Operation()
{
m_pComponent->Operation();
}
void ConcreateDecorator::AddedBehavior()
{
cout << "ConcreateDecorator::AddedBehavior()"<<endl;
}
void ConcreateDecorator::Operation()
{
//m_pComponent->Operation();
Decorator::Operation();
AddedBehavior();
}
void ConcreateComponent::Operation()
{
cout << "ConcreateComponent::Operation()"<<endl;
}
#include "stdafx.h"
#include <stdlib.h>
#include "Decorator.h"
int _tmain(int argc, _TCHAR* argv[])
{
Component* lpComponent = new ConcreateComponent;
Decorator* lpDecorator = new ConcreateDecorator(lpComponent);
lpDecorator->Operation();
delete lpDecorator;
lpDecorator = NULL;
system("pause");
return 0;
}