有时我们希望给某个对象而不是整个类添加一些功能。例如,一个图形用户界面工具箱允许你对任意一个用户界面组件添加一些特性,例如边框,或是一些行为,例如窗口滚动。(GoF)
下面请看示例程序:
#ifndef _COMPONENT_H
#define _COMPONENT_H
#include <iostream>
using std::cout;
using std::endl;
class virtualComponent
{
public:
virtual ~virtualComponent()
{
std::cout<<"Destructor of virtualComponent"<<endl;
}
virtual void Draw()
{
std::cout<<"virtualComponent::Draw()"<<std::endl;
}
private:
};
class TextView:public virtualComponent
{
public:
TextView(){std::cout<<"Constructor of TextView"<<endl;}
virtual ~TextView()
{
std::cout<<"Destructor of TextView"<<endl;
}
virtual void Draw()
{
std::cout<<"TextView::Draw()"<<std::endl;
}
private:
};
#endif
#ifndef _DECORATOR_H
#define _DECORATOR_H
#include "Component.h"
#include <iostream>
class Decorator:public virtualComponent
{
public:
Decorator(virtualComponent* component):_pComponent(component){}
virtual ~Decorator()
{
std::cout<<"Destructor of Decorator"<<endl;
if(_pComponent)
_pComponent->~virtualComponent();
}
virtual void Draw(){std::cout<<"Decorator::Draw()"<<std::endl;}
private:
virtualComponent* _pComponent;
};
class ScrollDecorator:public Decorator
{
public:
ScrollDecorator(virtualComponent* component, int scrollPosition=0):
Decorator(component),_scrollPosition(scrollPosition)
{
std::cout<<"Constructor of ScrollDecorator"<<endl;
}
virtual ~ScrollDecorator()
{
std::cout<<"Destructor of ScrollDecorator"<<endl;
}
virtual void Draw()
{
std::cout<<"ScrollDecorator::Draw()"<<endl;
ScrollTo();
}
virtual void ScrollTo(){std::cout<<"ScrollDecorator::ScrollTo()"<<endl;}
private:
int _scrollPosition;
};
class BorderDecorator:public Decorator
{
public:
BorderDecorator(virtualComponent* component, int borderWidth =0):
Decorator(component),_borderWidth(borderWidth)
{
std::cout<<"Constructor of BorderDecorator"<<endl;
}
virtual ~BorderDecorator()
{
std::cout<<"Destructor of BorderDecorator"<<endl;
}
virtual void Draw()
{
std::cout<<"BorderDecorator::Draw()"<<endl;
DrawBorder();
}
virtual void DrawBorder(){std::cout<<"BorderDecorator::DrawBorder()"<<endl;}
private:
int _borderWidth;
};
#endif
#include <iostream>
#include "Decorator.h"
int main()
{
Decorator* dec1= new ScrollDecorator(new TextView());
dec1->Draw();
Decorator* dec2= new ScrollDecorator(new BorderDecorator(new TextView()));
dec2->Draw();
delete dec1;
std::cout<<"--------------------------"<<endl;
delete dec2;
system("PAUSE");
}