旨在将请求沿着处理者链进行发送。收到请求后,每个处理者均可对请求进行处理,或将其传递给链上的下个处理者。
将请求的发送者和接受者解耦,并使请求随着处理对象链传递,优化系统内部处理逻辑
- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- __doc__ = """
- 责任链模式
- 例:一个产品生产流水线,需要三个环节:生产、质检、包装。每个环节只能由对应的工人处理,如果无法处理则传递给下一个环节处理。
- """
-
- from abc import ABC, abstractmethod
-
-
- class Worker(ABC):
- """抽象处理类"""
-
- @abstractmethod
- def handle_product(self, product):
- pass
-
- @abstractmethod
- def set_next_worker(self, worker):
- pass
-
-
- class Producer(Worker):
- """具体处理类"""
-
- def __init__(self):
- self.next_worker = None
-
- def set_next_worker(self, worker):
- self.next_worker = worker
-
- def handle_product(self, product):
- if product.get("process") == "produce":
- print("生产商正在生产产品")
- elif self.next_worker:
- self.next_worker.handle_product(product)
-
-
- class Inspector(Worker):
- """具体处理类"""
-
- def __init__(self):
- self.next_worker = None
-
- def set_next_worker(self, worker):
- self.next_worker = worker
-
- def handle_product(self, product):
- if product.get("process") == "inspect":
- print("检验员正在检验产品")
- elif self.next_worker:
- self.next_worker.handle_product(product)
-
-
- class Packer(Worker):
- """具体处理类"""
-
- def __init__(self):
- self.next_worker = None
-
- def set_next_worker(self, worker):
- self.next_worker = worker
-
- def handle_product(self, product):
- if product.get("process") == "pack":
- print("包装商正在包装产品")
- elif self.next_worker:
- self.next_worker.handle_product(product)
-
-
- if __name__ == "__main__":
- """
- 生产商正在生产产品
- 检验员正在检验产品
- 包装商正在包装产品
- """
- producer = Producer()
- inspector = Inspector()
- packer = Packer()
-
- producer.set_next_worker(inspector)
- inspector.set_next_worker(packer)
-
- product1 = {"process": "produce"}
- product2 = {"process": "inspect"}
- product3 = {"process": "pack"}
-
- producer.handle_product(product1)
- producer.handle_product(product2)
- producer.handle_product(product3)