dimanche 19 août 2018

Decorator Design Pattern vs composition of behaviours

I was reading about Decorator Design Pattern

Below is the general implementation in C++ (implementation 1)

class component
{
public:
    virtual void do_this() {}
};

class concerete_component : public component
{
public:
    void do_this()
    {
        cout << "doing concerete_component\n";
    }
};

class behaviour_decorator : public component
{
public:
    behaviour_decorator(component* c)
        : m_cmp(c) {}

    void do_this()
    {
        m_cmp->do_this();
    }

private:
    component * m_cmp;
};

class behaviour_a : public behaviour_decorator
{
public:
    behaviour_a(component* c)
        : behaviour_decorator(c) {}

    void do_this()
    {
        behaviour_decorator::do_this();
        cout << "doing behaviour_a\n";
    }
};

class behaviour_b : public behaviour_decorator
{
public:
    behaviour_b(component* c)
        : behaviour_decorator(c) {}

    void do_this()
    {
        behaviour_decorator::do_this();
        cout << "doing behaviour_b\n";
    }
};


int main()
{
    component* c = new behaviour_b(new behaviour_a(new concerete_component()));
    c->do_this();
    return 0;
}

Class Diagram

Or we can have another implementation to achieve the same behaviour (implementation 2)

class behaviour_decorator
{
public:
    virtual void do_this()
    {
    }
};

class behaviour_a : public behaviour_decorator
{
public:
    void do_this()
    {
        cout << "doing behaviour_a\n";
    }
};

class behaviour_b : public behaviour_decorator
{
public:
    void do_this()
    {
        cout << "doing behaviour_b\n";
    }
};

class component
{
public:
    virtual void do_this()
    {
        for (list <behaviour_decorator*>::iterator it = behaviours.begin();
            it != behaviours.end(); ++it)
        {
            (*it)->do_this();
        }
    }

    void add_behaviour(behaviour_decorator* b)
    {
        behaviours.push_back(b);
    }

private:
    list <behaviour_decorator*> behaviours;
};

class concerete_component : public component
{
public:
    void do_this()
    {
        cout << "doing concerete_component\n";
        component::do_this();
    }
};

int main()
{
    component* c = new concerete_component();
    c->add_behaviour(new behaviour_a());
    c->add_behaviour(new behaviour_b());
    c->do_this();
    return 0;
}

enter image description here

Is implementation 2 another way to implement decorator pattern? If not then what problem does implementation 1 solve that implementation 2 doesn't?

Thank you

Aucun commentaire:

Enregistrer un commentaire