程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python design pattern behavior pattern responsibility chain pattern

編輯:Python

Catalog

List of articles

  • Catalog
  • The chain of responsibility model
  • Application scenarios
  • Code example

The chain of responsibility model

The chain of responsibility model , Connect multiple processing methods into a chain , Requests will flow along the chain until a node in the chain can handle the request . Usually, this chain is formed by an object containing a reference to another object , Each node has a condition for the request , When the condition is not met, it will be passed to the next node for processing .

The responsibility chain model has several key points :

  1. An object contains a reference to another object, and so on to form a chain .
  2. There should be a clear division of responsibilities in each object , That is, the condition for processing the request .
  3. The last section of the chain should be designed for general request processing , To avoid loopholes .
  4. The request should be passed into the head of the chain .

Application scenarios

Code example

Entity role :

  • Abstract processor (Handler)
  • Specific handler (Concrete Handler)
  • client (Client)
import abc
# Abstract processor 
class Handler(metaclass=abc.ABCMeta):
@abc.abstractmethod
def handle(self, day):
pass
# Specific handler , As one of the chain nodes .
class GeneralManager(Handler):
def handle(self, day):
if day <= 10:
print(f" The general manager granted leave {
day} God ")
else:
print(" Too long vacation , No leave !")
# Specific handler , As one of the chain nodes .
class DivisionManager(Handler):
def __init__(self):
self.next = GeneralManager() # Link to the next level 
def handle(self, day):
if day <= 5:
print(f" The Department Manager granted leave {
day} God ")
else:
print(" Department managers are not qualified for leave ")
self.next.handle(day)
# Specific handler , As one of the chain nodes .
class ProjectManager(Handler):
def __init__(self):
self.next = DivisionManager() # Link to the next level 
def handle(self, day):
if day <= 3:
print(f" The project manager granted leave {
day} God ")
else:
print(" The project manager is not qualified for leave ")
self.next.handle(day)
if __name__ == "__main__":
handler = ProjectManager()
handler.handle(4)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved