设计模式之Chain of Responsibility模式

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模式的最大的一个有点就是给系统降低了耦合性,请求的发送者完全不必知道该请求会被哪个应答对象处理,极大地降低了系统的耦合性。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值