由于在开发过程中.由于需求的不断改变,可能要不断的为类添加新的功能,这样就要不断的继承现有的类,以致于继承的层次逐渐加深.为了避免这种情况发生,我们用另外一种方式来实现类的功能的增加,即Decorator模式.
先看一下代码:
class Component
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public;
Component();
virtual ~Component();
virtual void Operation();
};
class ChildCom:public Component
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public;
ChildCom();
~ChildCom();
void Operation();
};
class Decorator:public Component
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public:
Decorator(Component *);
~Decorator();
void Operation();
protected:
Component *_cmpt; //保留了父类的operation.
};
class ChildDecorator
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public:
ChildDecorator(Component *pCom):Decorator(pCom)
{}
~ChildDecorator();
void Operation()
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedSubBlock.gif)
{
_cmpt->Operation();
this->newAction();
}
void newAction(); //新添加的operation.
};
Component类为父类,ChildCom为Component的一个子类,假如在ChildCom上再添加一个行为的话,这时,创建一个Decorator抽象类继承于Component,然后创建一个子类,在这个子类中完成添加新功能...