Sunday, 22 November 2015

Design patterns - Chain of Responsibility in C++

Design patterns - Chain of Responsibility in Cpp with code examples:

This post will explains you how the objects are processing. For example, Filter/ColorMatch/RedEye/Rotator is the processing objects.





#include <QtGui/QApplication>

#include <iostream>

#include <string>

using namespace std;

class Picture

{

public:

    Picture(string s) : m_pcPicName(s)

    {

  cout << "Processing " << m_pcPicName << " ...\n";

    }

private:

    string m_pcPicName;

};

class PictureProcessor

{

public:

    PictureProcessor() : m_ocNextProcessor(0){ }

public:

    void process(Picture &p) {

        processImplementation(p);

        if (m_ocNextProcessor != 0)

            m_ocNextProcessor->process(p);

    }

    virtual ~PictureProcessor() { }

    void setNextProcessor(PictureProcessor *p) {

        m_ocNextProcessor = p;

    }

protected:

    virtual void processImplementation(Picture &a) = 0;

private:

    PictureProcessor *m_ocNextProcessor;

};

class Scale : public PictureProcessor

{

public:

    enum SCALE { S50, S100, S200, S300, S500 };

    Scale(SCALE s) : mSCALE(s) { }

private:

    void processImplementation(Picture &a) {

        cout << "Scaling Picture\n";

    }

    SCALE mSCALE;

};

class RedEye : public PictureProcessor

{

private:

    void processImplementation(Picture &a) {

        cout << "Removing red eye\n";

    }

};

class Filter : public PictureProcessor

{

private:

    void processImplementation(Picture &a) {

        cout << "Applying filters\n";

    }

};

class ColorMatch : public PictureProcessor

{

private:

    void processImplementation(Picture &a)

    {

        cout << "Matching colors\n";

    }

};


This is the function that is used to test the picture processing functions
void processPicture(Picture &pcPic)

{

    ColorMatch ocMatch;

    RedEye ocEye;

    Filter ocFilter;

    Scale scale(Scale::S200);

    scale.setNextProcessor(&ocEye);

    eye.setNextProcessor(&ocMatch);

    match.setNextProcessor(&ocFilter);

    scale.process(pcPic);

}


The mail application that is used to ca;; the Picture class to test the processing of the picture.
int main (int argc, char *argv[])

{

   QApplication a(argc, argv);

//   TabExample ocPush;

//   ocPush.show ();

   Picture *p = new Picture("Test Picture");

   processPicture(*p);

   return a.exec ();

}


In the above code each processing object contains implementation (processImplementation() in the code below) that defines the types of command objects that it can handle. The rest are passed to the next processing object in the chain.

No comments: