
- Python 設計模式教程
- Python 設計模式 - 首頁
- 引言
- Python 設計模式 - 要點
- 模型檢視控制器模式
- Python 設計模式 - 單例
- Python 設計模式 - 工廠
- Python 設計模式 - 生成器
- Python 設計模式 - 原型
- Python 設計模式 - 外觀
- Python 設計模式 - 命令
- Python 設計模式 - 介面卡
- Python 設計模式 - 裝飾器
- Python 設計模式 - 代理
- 職責鏈模式
- Python 設計模式 - 觀察者
- Python 設計模式 - 狀態
- Python 設計模式 - 策略
- Python 設計模式 - 模板
- Python 設計模式 - 享元
- 抽象工廠
- 面向物件
- 面向物件概念實現
- Python 設計模式 - 迭代器
- 字典
- 列表資料結構
- Python 設計模式 - 集合
- Python 設計模式 - 佇列
- 字串和序列化
- Python 中的並行性
- Python 設計模式 - 反模式
- 異常處理
- Python 設計模式資源
- 快速指南
- Python 設計模式 - 資源
- 討論
職責鏈模式
職責鏈模式用於實現軟體中的鬆散耦合,其中來自客戶端的指定請求透過其中包含的物件鏈傳遞。它有助於構建物件鏈。請求從一端進入並從一個物件移動到另一個物件。
此模式允許物件傳送命令,而不知道哪個物件將處理請求。
如何實現職責鏈模式?
我們現在將瞭解如何實現職責鏈模式。
class ReportFormat(object): PDF = 0 TEXT = 1 class Report(object): def __init__(self, format_): self.title = 'Monthly report' self.text = ['Things are going', 'really, really well.'] self.format_ = format_ class Handler(object): def __init__(self): self.nextHandler = None def handle(self, request): self.nextHandler.handle(request) class PDFHandler(Handler): def handle(self, request): if request.format_ == ReportFormat.PDF: self.output_report(request.title, request.text) else: super(PDFHandler, self).handle(request) def output_report(self, title, text): print '<html>' print ' <head>' print ' <title>%s</title>' % title print ' </head>' print ' <body>' for line in text: print ' <p>%s' % line print ' </body>' print '</html>' class TextHandler(Handler): def handle(self, request): if request.format_ == ReportFormat.TEXT: self.output_report(request.title, request.text) else: super(TextHandler, self).handle(request) def output_report(self, title, text): print 5*'*' + title + 5*'*' for line in text: print line class ErrorHandler(Handler): def handle(self, request): print "Invalid request" if __name__ == '__main__': report = Report(ReportFormat.TEXT) pdf_handler = PDFHandler() text_handler = TextHandler() pdf_handler.nextHandler = text_handler text_handler.nextHandler = ErrorHandler() pdf_handler.handle(report)
輸出
以上程式生成以下輸出 −

說明
以上程式碼為每月任務建立報告,它透過每個函式傳送命令。它採用兩個處理程式 - 用於 PDF 和用於文字。在所需的物件執行每個函式後,它列印輸出。
廣告