📅  最后修改于: 2020-11-07 09:07:29             🧑  作者: Mango
责任链模式用于在软件中实现松散耦合,其中来自客户端的指定请求通过其中包含的对象链传递。它有助于构建对象链。该请求从一端进入,然后从一个对象移动到另一对象。
此模式允许对象发送命令而无需知道哪个对象将处理请求。
现在,我们将看到如何实施责任链模式。
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 ''
print ' '
print ' %s ' % title
print ' '
print ' '
for line in text:
print ' %s' % line
print ' '
print ''
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和文本。一旦所需的对象执行了每个函数,它将打印输出。