把多个处理方法串成一个list。下一个list的节点是上一个list的属性。
每个节点都有判断是否能处理当前数据的方法。能处理,则直接处理,不能处理则调用下一个节点(也就是当前节点的属性)来进行处理。
Python 实现责任链模式,以request 的请求处理为例 :
1、RequestHandler 类:
基础的请求处理器类,定义了处理请求的接口和责任链的基本逻辑。
2、子类 GetRequestHandler, PostRequestHandler, PutRequestHandler, DeleteRequestHandler:
每个子类实现了 can_handle
方法和 handle
方法,根据请求的方法(GET, POST, PUT, DELETE)判断是否能够处理该请求,并实现具体的请求处理逻辑。
3、Usage 部分:
- 创建了一个示例的请求对象 Request,包含请求的方法 (
method
) 和 URL (url
)。 - 创建了四个请求处理器,并按照顺序构建了责任链:GET -> POST -> PUT -> DELETE。
- 调用
get_handler.handle_request(authentication_info_obj)
发起请求处理,结果会根据请求方法逐级传递到能够处理该请求的处理器,并返回处理结果。
class RequestHandler:def __init__(self, successor=None):self.successor = successordef handle_request(self, request):if not self.successor:raise NotImplementedError("A successor must be defined.")if self.can_handle(request):return self.handle(request)else:return self.successor.handle_request(request)def can_handle(self, request):raise NotImplementedError("Subclasses should implement this method.")def handle(self, request):raise NotImplementedError("Subclasses should implement this method.")class GetRequestHandler(RequestHandler):def can_handle(self, request):return request['method'] == 'GET' # Check if the method is GETdef handle(self, request):# Handle GET request logicreturn f"Handling GET request for {request['url']}"class PostRequestHandler(RequestHandler):def can_handle(self, request):return request['method'] == 'POST' # Check if the method is POSTdef handle(self, request):# Handle POST request logicreturn f"Handling POST request for {request['url']}"class PutRequestHandler(RequestHandler):def can_handle(self, request):return request['method'] == 'PUT' # Check if the method is PUTdef handle(self, request):# Handle PUT request logicreturn f"Handling PUT request for {request['url']}"class DeleteRequestHandler(RequestHandler):def can_handle(self, request):return request['method'] == 'DELETE' # Check if the method is DELETEdef handle(self, request):# Handle DELETE request logicreturn f"Handling DELETE request for {request['url']}"# Usage
if __name__ == "__main__":request_obj = {'method': 'GET', 'url': 'https://example.com'}# Create handlersdelete_handler = DeleteRequestHandler()put_handler = PutRequestHandler(delete_handler)post_handler = PostRequestHandler(put_handler)get_handler = GetRequestHandler(post_handler)# Example usageresult = get_handler.handle_request(request_obj)print(result)