装饰模式(Decorator),动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
//Decorator.h
#ifndef _DECORATOR_H
#define _DECORATOR_H
#include <string>
/*Component 类定义一个对象接口,可以给这些对象动态的添加指责*/
class Component
{
public:
Component();
virtual ~Component();
virtual void Operation()=0;
};
/*ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责*/
class ConcreteComponent:public Component
{
public:
ConcreteComponent();
virtual ~ConcreteComponent();
void Operation();
};
/*Decorator,装饰抽象类,从外类来扩展Component类的功能
但对于Component来说是无需知道Decorator的存在*/
class Decorator:public Component
{
protected:
Component* _com;
public:
Decorator(Component* cpt);
virtual ~Decorator();
void Operation();
};
/*具体的装饰对象,起到给Component添加职责的功能*/
class ConcreteDecoratorA:public Decorator
{
public:
std::string addState;
ConcreteDecoratorA(Component* cpt);
~ConcreteDecoratorA();
void Operation();
};
class ConcreteDecoratorB:public Decorator
{
public:
ConcreteDecoratorB(Component* cpt);
~ConcreteDecoratorB();
void Operation();
void AddedBehavior();
};
#endif//Decorator.cpp
#include "Decorator.h"
#include <iostream>
using namespace std;
Component::Component()
{
}
Component::~Component()
{
}
void Component::Operation()
{
}
ConcreteComponent::ConcreteComponent()
{
}
ConcreteComponent::~ConcreteComponent()
{
}
void ConcreteComponent::Operation()
{
cout<<"ConcreteComponent Operation"<<endl;
}
Decorator::Decorator(Component* cpt)
{
_com = cpt;
}
Decorator::~Decorator()
{
if (!_com)
{
delete _com;
}
}
void Decorator::Operation()
{
_com->Operation();
}
ConcreteDecoratorA::ConcreteDecoratorA(Component* cpt):Decorator(cpt)
{
}
ConcreteDecoratorA::~ConcreteDecoratorA()
{
}
void ConcreteDecoratorA::Operation()
{
//先执行父类的operation方法,然后在执行本子类特有的功能
//相当于对于原Component进行了装饰
Decorator::Operation();
addState = "New state";
cout<<addState<<endl;
}
ConcreteDecoratorB::ConcreteDecoratorB(Component* cpt):Decorator(cpt)
{
}
ConcreteDecoratorB::~ConcreteDecoratorB()
{
}
void ConcreteDecoratorB::Operation()
{
Decorator::Operation();
AddedBehavior();
}
void ConcreteDecoratorB::AddedBehavior()
{
cout<<"Added behavior from ConcreteDecoratorB"<<endl;
}//main.cpp
#include <iostream>
#include "Decorator.h"
int main()
{
Component* cpt = new ConcreteComponent();
ConcreteDecoratorA* da = new ConcreteDecoratorA(cpt);
ConcreteDecoratorB* db = new ConcreteDecoratorB(da);
db->Operation();
return 0;
}
本文详细介绍了装饰模式的概念及其在软件设计中的应用。通过示例代码解释了如何动态地为对象添加新的职责,同时保持原有功能不变。展示了装饰模式相比于继承的优势,并提供了具体的实现案例。
1542

被折叠的 条评论
为什么被折叠?



