ห่วงโซ่ความรับผิดชอบ
รูปแบบความรับผิดชอบถูกนำมาใช้เพื่อให้เกิดการเชื่อมต่อแบบหลวม ๆ ในซอฟต์แวร์ที่มีการส่งคำขอที่ระบุจากไคลเอนต์ผ่านห่วงโซ่ของวัตถุที่รวมอยู่ในนั้น ช่วยในการสร้างห่วงโซ่ของวัตถุ คำขอเข้าจากปลายด้านหนึ่งและย้ายจากวัตถุหนึ่งไปยังอีกวัตถุหนึ่ง
รูปแบบนี้อนุญาตให้อ็อบเจ็กต์ส่งคำสั่งโดยไม่ทราบว่าอ็อบเจ็กต์ใดจะจัดการกับคำร้องขอ
จะดำเนินการตามรูปแบบความรับผิดชอบอย่างไร?
ตอนนี้เราจะดูวิธีการนำรูปแบบห่วงโซ่ความรับผิดชอบไปใช้
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 และสำหรับข้อความ พิมพ์ผลลัพธ์เมื่อวัตถุที่ต้องการเรียกใช้แต่ละฟังก์ชัน