设计模式:行为模式:职责链(chain of responsibility)

http://www.bogotobogo.com/DesignPatterns/chain_of_responsibility.php

Chain of Responsibility

Chain-of-responsibility pattern is a design pattern consisting of a series of processing objects.




For example, Filter/ColorMatch/RedEye/Rotator are the processing objects as in the code below. 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.


#include 
#include 
using namespace std;

class Photo 
{
public:
    Photo(string s) : mTitle(s) 
    {
	cout << "Processing " << mTitle << " ...\n";
    }

private:
    string mTitle;
};

class PhotoProcessor
{
public:
    PhotoProcessor() : mNextProcessor(0){ }

public:
    void process(Photo &p) {
        processImplementation(p);
        if (mNextProcessor != 0) 
            mNextProcessor->process(p);
    }

    virtual ~PhotoProcessor() { }

    void setNextProcessor(PhotoProcessor *p) {
        mNextProcessor = p;
    }

protected:
    virtual void processImplementation(Photo &a) = 0;

private:
    PhotoProcessor *mNextProcessor;
};

class Scale : public PhotoProcessor
{
public:
    enum SCALE { S50, S100, S200, S300, S500 };
    Scale(SCALE s) : mSCALE(s) { }

private:
    void processImplementation(Photo &a) {
        cout << "Scaling photo\n";
    }

    SCALE mSCALE;
};

class RedEye : public PhotoProcessor
{
private:
    void processImplementation(Photo &a) {
        cout << "Removing red eye\n";
    }
};

class Filter : public PhotoProcessor
{
private:
    void processImplementation(Photo &a) {
        cout << "Applying filters\n";
    }
};

class ColorMatch : public PhotoProcessor
{
private:
    void processImplementation(Photo &a)
    {
        cout << "Matching colors\n";
    }
};

void processPhoto(Photo &photo)
{   
    ColorMatch match;
    RedEye eye;
    Filter filter;
    Scale scale(Scale::S200);
    scale.setNextProcessor(&eye);
    eye.setNextProcessor(&match);
    match.setNextProcessor(&filter);
    scale.process(photo);
}

int main()
{
    Photo *p = new Photo("Y2013 Photo");
    processPhoto(*p);
    return 0;
}

Output:

Processing Y2013 Photo ...
Scaling photo
Removing red eye
Matching colors
Applying filters

你可能感兴趣的:(行为模式,设计模式,C++)