Design Patterns - Decorator - Example 3


#include <iostream>
#include <string>

using namespace std;

class I {
  public:
    virtual ~I(){}
    virtual void doIt()  = 0;
};


class A : public I {
  public:
    ~A() {
      cout << "A dtor" << endl;
    }

    virtual void doIt() {
      cout << "A";
    }
};

class D : public I {
  public:
    D(I *inner) {
      m_wrapee = inner;
    }
    ~D() {
      delete m_wrapee;
    }

    virtual void doIt() {
      m_wrapee->doIt();
    }

  private:
    I *m_wrapee;
};

class X : public D {
  public:
    X(I *core): D(core) {}
    ~X() {
      cout << "X dtor" << endl;
    }

    void doIt() {
      D::doIt();
      cout << "X";
    }
};

class Y : public D {
  public:
    Y(I *core): D(core) {}
    ~Y() {
      cout << "Y dtor" << endl;
    }

    void doIt() {
      D::doIt();
      cout << "Y";
    }
};

class Z : public D {
  public:
    Z(I *core): D(core) {}
    ~Z() {
      cout << "Z dtor" << endl;
    }

    void doIt() {
      D::doIt();
      cout << "Z";
    }
};


int main(int argc, char **argv) {
  I *anX = new X(new A);
  I *anXY = new Y(new X(new A));
  I *anXYZ = new Z(new Y(new X(new A)));

  anX->doIt();
  cout << endl;

  anXY->doIt();
  cout << endl;

  anXYZ->doIt();
  cout << endl;

  return 0;
}