Decorator模式,也即装饰器模式,主要是在原有系统的基础上增加新的特色或者新的功能。我们认为Component是公有的父类,而ConcreteComponent类则是原有的已经实现的类,而当ConcreteComponent,功能已经不能满足我们的需求了,而新的功能的添加则是用到了Decorator模式,Decorator首先继承自Component,因为我们的Decorator的类,会不同于adapter模式,提供和ConcreteComponent一样的接口,ConcreteDecorator模式利用组合的模式获得ConcreteComponent的指针,然后呢,在提供对外接口的同时添加自己的特色,也因而提供了装饰的功能!!!!!也即装饰器模式,就是增加功能的设计模式!!!!!
主要是用于系统的更新等状况,可以这样认为,当我们为一个已经定义好的类,添加新的功能,通常情况下,我们继承该类来实现,通过继承还会加大继承的复杂度因为集成的深度会加深,所以我们要通过组合来实现现在先用Decorator模式图像,而Decorator模式最重要的特点就是,为已有功能增加特点!!!!!增加功能!!!!
代码是:
#include<iostream><iostream>
using namesoace std;
class Component
{
public:
virtual void Operation()
{
;
}
protected:
Component()
{
;
}
public:
~Component()
{;}
};
class ConcreteComponent:public Component
{
public:
ConcreteComponent()
{;}
~ConcreteComponent()
{;}
void Operation()
{;}
};
class Decorator:public Component
{
public:
Decorator(Component* Com)
{
m_com=Com;
}
~Decorator()
{;}
void Operation()
{;}
private:
Component* m_com;
};
class ConcreteDecorator:public Decorator
{
public:
ConcreteDecorator(Component*Com):Decorator(com)
{
m_com=Com;
}
~ConcreteDecorator()
{
delete m_com;
}
void AddBehavior()
{
//这里添加新的功能
}
void Operation()
{
m_com->Operation();
this->AddBehaivor();
}
};
int main()
{
Component* com=new ConcreteComponent();
Decorator* Dec=new ConcreteDecorator(com);
Dec->Operation();
}
</iostream>
这里有两个要注意的地方,一个是Decorator类是继承自Component,因为呢,我们始终要使用的是Component类型的指针,并且是要增加功能,那么其原有的功能还是要
ConcreteComponent自身来实现的,这里用的是指针的方式,调用原方法Operation,而后调用新增加的类的AddBehavior方法,这样就达到了增加原有类的功能的结果。