您的位置:首页 > 大数据 > 人工智能

设计模式之Chain of Responsibility模式

2013-07-09 16:10 204 查看
Responsibility.h


#ifndef _RESPONSIBILITY_H_
#define _RESPONSIBILITY_H_
class CHandler
{
public:
	CHandler();
	CHandler(CHandler *succ);
	virtual ~CHandler();
	virtual void HandlerQuestion()=0;
	void SetSuccessor(CHandler *succ);
	CHandler* GetSuccessor();
private:
	CHandler *m_succ;

};

class CConcreteHandlerA:public CHandler
{
public:
	CConcreteHandlerA(CHandler *succ);
	CConcreteHandlerA();
	~CConcreteHandlerA();
	void HandlerQuestion();
};

class CConcreteHandlerB:public CHandler
{
public:
	CConcreteHandlerB(CHandler *succ);
	CConcreteHandlerB();
	~CConcreteHandlerB();
	void HandlerQuestion();
};
#endif


Responsibility.cpp
#include <iostream>
#include <assert.h>
#include "Responsibilty.h"
using namespace std;
CHandler::CHandler()
{
	m_succ=0;
}

CHandler::CHandler(CHandler *succ)
{
	m_succ=succ;
}

CHandler::~CHandler()
{
	if(m_succ)
	{
		delete m_succ;
		m_succ=0;
	}
}

void CHandler::SetSuccessor(CHandler *succ)
{
	assert(succ);
	m_succ=succ;
}

CHandler * CHandler::GetSuccessor()
{
	return m_succ;
}

CConcreteHandlerA::CConcreteHandlerA()
{

}

CConcreteHandlerA::CConcreteHandlerA(CHandler *succ):CHandler(succ)
{

}

CConcreteHandlerA::~CConcreteHandlerA()
{

}

void CConcreteHandlerA::HandlerQuestion()
{
	if(this->GetSuccessor())
	{
		cout<<"Give the Handler to the successor of the HandlerA"<<endl;
		this->GetSuccessor()->HandlerQuestion();
	}
	else
	{
		cout<<"I do it alone"<<endl;
	}
}

CConcreteHandlerB::CConcreteHandlerB()
{

}

CConcreteHandlerB::CConcreteHandlerB(CHandler *succ):CHandler(succ)
{

}

CConcreteHandlerB::~CConcreteHandlerB()
{

}

void CConcreteHandlerB::HandlerQuestion()
{
	if(this->GetSuccessor())
	{
		cout<<"Give the Handler to the successor of the HandlerB"<<endl;
		this->GetSuccessor()->HandlerQuestion();
	}
	else
	{
		cout<<"B do it alone"<<endl;
	}

}


Chain of Responsibility模式的最大的一个有点就是给系统降低了耦合性,请求的发送者完全不必知道该请求会被哪个应答对象处理,极大地降低了系统的耦合性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: