概念解析
职责模式,也被称为“职责链模式”,其设计目的是为了避免请求发送者和接受者耦合在一起,而是将接受对象连接,形成职责链,知道有对象处理。客户不需要知道请求处理者的明确信息和处理的具体逻辑,需要进行请求发送即可。其设计要点如下:
- 需要明确请求者和请求内容。
- 明确有哪些责任人并对责任人进行抽象
- 责任人可以自由组合
其优点是:
- 降低耦合度,请求的接受者和发送者解耦
- 简化对象:对象不需要知道职责链结构
- 职责传递更灵活
- 增加新的处理类很方便
其缺点是:
- 无法保证请求一定被接受
- 可能造成循环调用
类图如下:
设计模板
职责模式代码样例如下,关键在于 NextHanler的传递
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from abc import ABCMeta, abstractmethod
class Request:
"请求内容"
def __init__(self, name, dayoff, reason):
self.__name = name
self.__dayoff = dayoff
self.__reson = reason
self.__leader = None
def getDayoff(self):
return self.__dayoff
def getReason(self):
return self.__person
class Responsible(metaclass=ABCMeta):
"责任人抽象类"
def __init__(self, name, title):
self.__name = name
self.__title = title
self._nextHandler = None
def getName(self):
return self.__name
def getTitle(self):
return self.__title
def setNextHandler(self, nextHandler):
self._nextHandler = nextHandler
def getNextHandler(self):
return self._nextHandler
def handleRequest(self, request):
"请求处理"
self._hanleRequestImpl(request)
# 如果存在下一个责任人,则进行责任传递
if (self._nextHandler is not None):
self._nextHandler.handleRequest(request)
@abstractmethod
def _handleRequestImpl(self, request):
"待实现的处理请求方法"
pass
实例分析
场景:请假批准,需要多个上级进行批准
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Person:
"请求者"
def __init__(self, name):
self.__name = name
self.__leader = None
def setName(self, name):
self.__name = name
def getName(self):
return self.__name
def setLeader(self):
return self.__leader
def sendRequest(self, request):
print("%s 申请请假 %d 天。请假事由: %s" % (self.__name, request.getDayoff(), request.getReason()))
if (self.__leader is not None):
self.__leader.handleRequest(request)
class Supervisor(Responsible):
"主管"
def __init__(self, name, title):
super().__init__(name, title)
def _handleRequestImpl(self, request):
if (request.getDayOff() <= 2):
print("同意 %s 请假,签字人:%s(%s)" % (request.getName(), self.getName(), self.getTitle()))
class DepartmentManager(Responsible):
"部门总监"
def __init__(self, name, title):
super().__init__(name, title)
def _handleRequestImpl(self, request):
if (request.getDayOff() > 2):
print("同意 %s 请假,签字人:%s(%s)" % (request.getName(), self.getName(), self.getTitle()))
class Administrator(Responsible):
"行政"
def __init__(self, name, title):
super().__init__(name, title)
def _handleRequestImpl(self, request):
print("%s 的请假申请已审核,情况属实!已备案处理,处理人:%s(%s)\n" %
(request.getName(), self.getName(), self.getTitle()))