1. 程式人生 > >用程式碼和UML圖化解設計模式之《責任鏈模式》

用程式碼和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       [email protected]  
@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;
}