Chain of Responsibility Design Pattern

Beginner

2019-03-26

Chain of Responsibility Pattern

Chain of responsibility pattern provides a way to decouple the sender of the request and the receiver.

The sender doesn't know about which handler will handle the request, it just fires a request and the appropriate handler will handle it.

The pattern is useful when you have a large set of request handler each depends on a specific type or condition to know it the requests belongs to it or not.

for example : you might have a billing system with three handlers for invoices each one operates on a range. and depending on the range a prize will be given. or another action will be taken.

In this case you will have LowInvoiceHandler, NormalInvoiceHandler and HighInvoiceHandler . Each one check to see if the requests ( invoice ) belongs to it or not, if so, it will handle it , if no , it will delegate the request to the next handle to handle it ... and so on.

Problem

the problems that the chain of responsibility pattern tries to solve

  • Coupling between the request sender and receiver
  • Request tracking logic is bound to the sender
  • Separate responsibilities among several components each is responsible for handling a different kind
  • It implements launch-and-leave pattern, where the sender launches the request and let the appropriate handler process it.


Structure

The Chain of Responsibility Pattern usually consists of a common abstract Handler that contains a definition for the handle method and a reference to the next handler.

Chain of Responsibility


Example Code


Each concrete handler class inherits from the abstract handler class. if the Invoice range is withing the handler class range, it will handle it. otherwise it will parse it to the next handler if it's not null ( if there is one available ).