Decorator pattern and Proxy pattern
You want to add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class.
Typical Example as follows, with the typical traits of attaching additional responsibilities to an object dynamically.
Widget* aWidget = new BorderDecorator(
new ScrollDecorator(
new TextWidget( 80, 24 )
)
)
);
aWidget->draw();
The Famous Remark:
Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface. [GOF, p216]
Decorator is designed to let you add responsibilities to objects without subclassing. Composite's focus is not on embellishment but on representation. These intents are distinct but complementary. Consequently, Composite and Decorator are often used in concert. [GOF, p220]
Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests. [GOF, p220]
Decorator lets you change the skin of an object. Strategy lets you change the guts. [GOF, p184]
The code for the calling class above, the routines should like that:
// Decorator.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Widget{
public:
virtual void draw()= 0;
};
class TextWidget:public Widget{
public:
TextWidget(int w, int h){
_w = w; _h = h;
}
void draw(){
cout<<"TextWidget..."<<endl;
//...Some real draw action....
};
protected:
Widget* _widget;
int _w, _h;
};
class Decorator: public Widget{
public:
Decorator(Widget* w){
_widget = w;
}
void draw(){
cout<<"Decorator..."<<endl;
_widget->draw();
}
protected:
Widget* _widget;
};
class ScrollDecorator: public Decorator{
public:
ScrollDecorator(Widget* w):Decorator(w){};
void draw(){
cout<<"ScorllDecorator..."<<endl;
_widget->draw();
}
};
class BorderDecorator: public Decorator{
public:
BorderDecorator(Widget* w):Decorator(w){};
void draw(){
cout<<"BorderDecorator.."<<endl;
_widget->draw();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Widget* aWidget = new BorderDecorator(
new ScrollDecorator(
new TextWidget( 80, 24 )
)
);
aWidget->draw();
return 0;
}
There is some mistakes in the routines above.
_widget->draw() just get Widget instance to do draw(), but it has not call the Decorator, so it should be Decorator::draw() to do the real draw().