1. 责任链模式(Chain of Responsibility)介绍
UML类图
定义
使多个对象都有机会处理请求,从而避免了请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。
责任链模式的结构
责任链模式的类图非常简单,它由一个抽象地处理类和它的一组实现类组成:
- 抽象处理类:抽象处理类中主要包含一个指向下一处理类的成员变量nextHandler和一个处理请求的方法handRequest,handRequest方法的主要主要思想是,如果满足处理的条件,则有本处理类来进行处理,否则由nextHandler来处理。
- 具体处理类:具体处理类主要是对具体的处理逻辑和处理的适用条件进行实现。
2. 示例
- 了解了责任链模式的大体思想之后,再看代码就比较好理解了。
- 下面代码中Level类是模拟判定条件;Request,Response分别对应请求和响应;抽象类Handler中主要进行条件的判断,这里模拟一个处理等级,只有处理类的处理等级高于Request的等级才能处理,否则交给下一个处理者处理。在Client类中设置好链的前后执行关系,执行时将请求交给第一个处理类,这就是责任链模式。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''Chain of Responsibility Pattern with Python Code
'''
from abc import abstractmethod, ABCMeta
class Level(object):
num = 0
def __init__(self, num):
self.num = num
def above(self, level):
if(self.num >= level.num):
return True
return False
class Request(object):
level = None
def __init__(self, level):
self.level = level
def getLevel(self):
return self.level
class Response(object):
pass
class Handler(metaclass=ABCMeta):
nextHandler = None
def handleRequest(self, request):
response = None
if self.getHandlerLevel().above(request.getLevel()):
response = self.response(request);
else:
if self.nextHandler != None:
response = self.nextHandler.handleRequest(request)
else:
print("deny access")
return response
def setNextHandler(self, handler):
self.nextHandler = handler
@abstractmethod
def getHandlerLevel(self):
pass
@abstractmethod
def response(self, request):
pass
class ConcreteHandler1(Handler):
def getHandlerLevel(self):
return Level(10)
def response(self, request):
print("Level 1 access")
return Response()
class ConcreteHandler2(Handler):
def getHandlerLevel(self):
return Level(100)
def response(self, request):
print("Level 2 access")
return Response()
class ConcreteHandler3(Handler):
def getHandlerLevel(self):
return Level(1000)
def response(self, request):
print("Level 3 access")
return Response()
class Client(object):
def main(self):
handler1 = ConcreteHandler1()
handler2 = ConcreteHandler2()
handler3 = ConcreteHandler3()
handler1.setNextHandler(handler2)
handler2.setNextHandler(handler3)
response = handler1.handleRequest(Request(Level(500)))
if __name__ == "__main__":
Client().main()
输出:
# ./ChainofResponsibility.py
Level 3 access
参考:
https://wiki.jikexueyuan.com/project/java-design-pattern/chain-responsibility-pattern.html
https://www.runoob.com/design-pattern/chain-of-responsibility-pattern.html