用代码和UML图化解设计模式之《责任链模式》


责任链模式,用我的理解就是动作的处理链表。根据请求的不同类型,在链表查找相应类型的处理者。处理者是一个链表。

wiki上说明

wikipedia的定义为:CoR pattern consists of a source of command objects and a series of processing objects. Each processing object contains a set of logic that describes the types of command objects that it can handle, and how to pass off those that it cannot handle to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.

 

用下面的一个图来解释

 

基本的UML图为

// ChainofResponsibility.cpp : 定义控制台应用程序的入口点。
//************************************************************************/    
/* @filename    ChainofResponsibility.cpp
@author       wallwind  
@createtime    2012/11/6 11:58
@function     责任链模式
@email       wochenglin@qq.com  
@weibo      @成林有理想
*/    
/************************************************************************/

#include "stdafx.h"
#include <iostream>

using namespace std;

class IChain
{
public:
	IChain():m_nextChain(NULL)
	{

	}
	virtual ~IChain()
	{
		if (m_nextChain !=NULL)
		{
			delete m_nextChain;
			m_nextChain = NULL;
		}
	}

	void setChainHandler(IChain* handler)
	{
		m_nextChain = handler;
	}
	virtual void handleReq(int reqtype) = 0;

	
protected:
	IChain* m_nextChain;
	
};

class FirstHandler:public IChain
{
public:
	FirstHandler():IChain()
	{
	}
	virtual ~FirstHandler(){}

	virtual void handleReq(int reqtype)
	{
		if (reqtype <3)
		{
			cout<<"FirstHandler::handleReq"<<endl;
		}
		else if (m_nextChain !=NULL)
		{
			m_nextChain->handleReq(reqtype);
		}
		else
		{
			cout<<"no handler"<<endl;
		}
	}
};

class SecondHandler:public IChain
{
public:
	SecondHandler():IChain()
	{
		
	}
	virtual ~SecondHandler(){}

	virtual void handleReq(int reqtype)
	{
		if (reqtype <7)
		{
			cout<<"SecondHandler::handleReq"<<endl;
		}
		else if (m_nextChain !=NULL)
		{
			m_nextChain->handleReq(reqtype);
		}
		else
		{
			cout<<"no handler"<<endl;
		}
	}


	
};

class ThirdHandler:public IChain
{
public:
	ThirdHandler():IChain()
	{
	}
	virtual ~ThirdHandler(){}

	virtual void handleReq(int reqtype)
	{
		if (reqtype <9)
		{
			cout<<"ThirdHandler::handleReq"<<endl;
		}
		else if (m_nextChain !=NULL)
		{
			m_nextChain->handleReq(reqtype);
		}
		else
		{
			cout<<"no handler"<<endl;
		}
	}


};

int _tmain(int argc, _TCHAR* argv[])
{

	IChain *p1handler= new FirstHandler;
	IChain *p2handler= new SecondHandler;
	IChain *p3handler= new ThirdHandler;

	p1handler ->setChainHandler(p2handler);
	p2handler->setChainHandler(p3handler);

	p3handler ->handleReq(4);

	delete p1handler,p2handler,p3handler;
	return 0;
}

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值