All Courses

Chain of Responsibility

Neha Kumawat

3 years ago

The chain of responsibility pattern is used to achieve loose coupling in software where a specified request from the client is passed through a chain of objects included in it. It helps in building a chain of objects. The request enters from one end and moves from one object to another.
This pattern allows an object to send a command without knowing which object will handle the request.

How to implement the chain of responsibility pattern?

We will now see how to implement the chain of responsibility pattern.

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):

class PDFHandler(Handler):

   def handle(self, request):
      if request.format_ == ReportFormat.PDF:
         self.output_report(request.title, request.text)
         super(PDFHandler, self).handle(request)
   def output_report(self, title, text):
      print ''
      print ' '
      print ' %s' % title
      print ' '
      print ' '
      for line in text:
         print ' %s

Submit Review