Click here to Skip to main content
15,887,746 members
Articles / Programming Languages / C++

Building Decorator Chains

Rate me:
Please Sign up or sign in to vote.
4.50/5 (4 votes)
22 Oct 2010CPOL3 min read 29.8K   136   23  
The article explains a method, how flexible and extendible decorator chains can be built in a generic way. Its power is best seen if it is used with boost::factory and boost::bind.
#include <iostream>
#include <string>

#include <boost/functional/factory.hpp>
#include <boost/bind.hpp>
#include <boost/bind/placeholders.hpp>

#include "decorator_chain.hpp"

using namespace std;

class abstract_class
{
public:

    virtual void do_something( int a , int b ) = 0;
};

class concrete_class_a : public abstract_class
{
    int m_value;

public:

    concrete_class_a( int value )
    : m_value( value ) { }

    void do_something( int a , int b )
    {
        cout << "concrete_class_a : " << m_value << "\t" << a << "\t" << b << "\n";
    }

};

class concrete_class_b : public abstract_class
{
    string &m_str;

public:

    concrete_class_b( string &str )
    : m_str( str ) { }

    void do_something( int a , int b )
    {
        cout << "concrete_class_b : " << m_str << "\t" << a << "\t" << b << "\n";
    }
};


class decorator_a : public abstract_class
{
    abstract_class *m_decoratedClass;
    int m_value;

public:

    decorator_a( abstract_class *decoratedClass , int value )
    : m_decoratedClass( decoratedClass ) , m_value( value ) { }

    void do_something( int a , int b )
    {
        m_decoratedClass->do_something( a , b );
        cout << "decorator_a : " << m_value << "\t" << a << "\t" << b << "\n";
    }
};

class decorator_b : public abstract_class
{
    abstract_class *m_decoratedClass;
    string m_str;

public:

    decorator_b( abstract_class *decoratedClass , const string &str )
    : m_decoratedClass( decoratedClass ) , m_str( str ) { }

    void do_something( int a , int b )
    {
        m_decoratedClass->do_something( a , b );
        cout << "decorator_b : " << m_str << "\t" << a << "\t" << b << "\n";
    }
};

int main( int argc , char **argv )
{
    string str = "main";

    concrete_class_a c1( 10 );
    concrete_class_b c2( str );

    decorator_a d1( &c1 , 22 );
    decorator_b d2( &c2 , "Hello!" );

    d1.do_something( 2 , 3 );
    d2.do_something( 4 , 5 );



    return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions