设计模式之职责链

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012532305/article/details/50722666


     职责链模式就是针对一个请求,沿着一条对此请求有处理权的对象链依次处理,直到此次请求被处理掉而结束 。可以结合一些生活中的场景就比较容易理解了,比如在公司的请假审批流程,一般是层层向上级领导推进,直到这个请假被批准终止。代码如下:


// ChainOfResponsibility.cpp : 定义控制台应用程序的入口点。
//

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

class Handler{
public:
	Handler(int maxAuthority): m_iMaxAuthority(maxAuthority){}
	~Handler(){}
	void Handle(int authority){
		if (IsCanHandle(authority)){
			printf("0X%p Handle!\n", this);
		}else{
			printf("0X%p Exceed My Authority!\n", this);
			if (m_pSuper){
				m_pSuper->Handle(authority);
			}
		}
	}
	void SetSuperHandler(Handler* pHandler){
		m_pSuper = pHandler;
	}
protected:
	bool IsCanHandle(int authority){
		return m_iMaxAuthority >= authority;
	}
	int m_iMaxAuthority;
	Handler* m_pSuper;
};

int _tmain(int argc, _TCHAR* argv[])
{
	Handler h1(3), h2(5), h3(7);
	h1.SetSuperHandler(&h2);
	h2.SetSuperHandler(&h3);
	h1.Handle(6);
	system("@pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/u012532305/article/details/50722666
今日推荐