Python设计模式之责任链模式

责任链模式学习链接

#!/usr/bin/python
# coding:utf8
"""
责任链模式
"""


class Manager():
	"""经理类"""
	successor = None
	name = ''

	def __init__(self, name):
		self.name = name

	def setSuccessor(self, successor):
		# 设置上级
		self.successor = successor

	def handleRequest(self, request):
		# 处理请求
		pass


class LineManager(Manager):
	'''直属经理'''

	def handleRequest(self, request):
		if request.requestType == 'DaysOff' and request.number <= 3:
			return '%s:%s Num:%d Accepted OVER' % (self.name, request.requestContent, request.number)
		else:
			if self.successor != None:
				self.successor.handleRequest(request)
				print('%s:%s Num:%d Accepted CONTINUE' % (self.name, request.requestContent, request.number))


class DepartmentManager(Manager):
	'''部门经理'''

	def handleRequest(self, request):
		if request.requestType == 'DaysOff' and request.number <= 7:
			return '%s:%s Num:%d Accepted OVER' % (self.name, request.requestContent, request.number)
		else:
			if self.successor != None:
				self.successor.handleRequest(request)
				print('%s:%s Num:%d Accepted CONTINUE' % (self.name, request.requestContent, request.number))

class GeneralManager(Manager):
	'''总经理'''

	def handleRequest(self, request):
		if request.requestType == 'DaysOff':
			return '%s:%s Num:%d Accepted OVER' % (self.name, request.requestContent, request.number)


class Request():
	def __init__(self, requestType, requestContent, number=0):
		self.requestType = requestType
		self.requestContent = requestContent
		self.number = number

	def commit(self, generalManager):
		ret = generalManager.handleRequest(self)
		print(ret)
		return ret


if __name__ == "__main__":
	line_manager = LineManager('LINE MANAGER')
	department_manager = DepartmentManager('DEPARTMENT MANAGER')
	general_manager = GeneralManager('GENERAL MANAGER')
	line_manager.setSuccessor(department_manager)
	department_manager.setSuccessor(general_manager)
	request = Request(requestContent="'Ask 1 day off'", requestType='DaysOff', number=1)
	request.commit(line_manager)
	request = Request(requestContent="'Ask 5 day off'", requestType='DaysOff', number=5)
	request.commit(line_manager)
	request = Request(requestContent="'Ask 10 day off'", requestType='DaysOff', number=10)
	request.commit(line_manager)

 

    原文作者:勿在浮沙筑高台LS
    原文地址: https://blog.csdn.net/baidu_15113429/article/details/85760002
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞