Decorator design pattern ( C++ )

P

Pallav singh

#include <iostream>

using namespace std;

/* Component (interface) */
class Widget {

public:
virtual void draw() = 0;
virtual ~Widget() {}
};


/* ConcreteComponent */
class TextField : public Widget {

private:
int width, height;

public:
TextField( int w, int h ){
width = w;
height = h;
}
void draw() {
cout << "TextField: " << width << ", " << height << '\n';
}
};


/* Decorator (interface) */
class Decorator : public Widget {

private:
Widget* wid; // reference to Widget
public:
Decorator( Widget* w ) {
wid = w;
}
void draw() {
wid->draw();
}

~Decorator() {
delete wid;
}
};

/* ConcreteDecoratorA */
class BorderDecorator : public Decorator {

public:
BorderDecorator( Widget* w ) : Decorator( w ) { }
void draw() {
Decorator::draw();
cout << " BorderDecorator" << '\n';
}
};

/* ConcreteDecoratorB */
class ScrollDecorator : public Decorator {
public:
ScrollDecorator( Widget* w ) : Decorator( w ) { }
void draw() {
Decorator::draw();
cout << " ScrollDecorator" << '\n';
}
};

int main( void ) {

Widget* aWidget = new BorderDecorator( new ScrollDecorator( new
TextField( 80, 24 )));

aWidget->draw();

delete aWidget;
}

+++++++++++++++++++++++++++++++++++++++++++
How does interface property changes here ?

it will call draw( ) function in following order
1. TextField
2. ScrollDecorator
3. BorderDecorator

Is it Following RAII( Resource Acquisition is Order of
initialization ) principle of C++ ?

How are virtual function helping it ?

++++++++++++++++++++++++++++++++++++++++++
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top