Decorator design pattern ( C++ )

Discussion in 'C++' started by Pallav singh, Aug 6, 2008.

  1. Pallav singh

    Pallav singh Guest

    #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 ?

    ++++++++++++++++++++++++++++++++++++++++++
     
    Pallav singh, Aug 6, 2008
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jean Lutrin
    Replies:
    8
    Views:
    700
    Chris Uppal
    Nov 18, 2004
  2. Gregory
    Replies:
    3
    Views:
    370
    Gregory
    Dec 15, 2006
  3. Pallav singh
    Replies:
    0
    Views:
    412
    Pallav singh
    Jan 22, 2012
  4. Pallav singh
    Replies:
    0
    Views:
    434
    Pallav singh
    Jan 22, 2012
  5. Pallav singh
    Replies:
    1
    Views:
    475
    Peter Remmers
    Jan 22, 2012
Loading...

Share This Page