设计模式:行为模式:职责链(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 <iostream>
#include <string>
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值