Chain of Responsibility Pattern
This lesson discusses the chain of responsibility pattern in detail with the aid of a coding example.
We'll cover the following...
What is the chain of responsibility pattern?
The chain of responsibility pattern allows a request sent by a client to be received by more than one object. It creates a chain of loosely-coupled objects that, upon receiving the request, either handle it or pass it to the next handler object.
A common example of this pattern is event bubbling in DOM. An event propagates through different nested elements of the DOM until one of them handles it.
Example #
Explanation
The example above implements the chain of responsibility pattern to check if a given number is a multiple of two, three, or five.
This example is for positive multiples only.
So, how do we want to implement this functionality? We want to give a number and let the handlers in the chain decide if they’re going to process it or pass it to the next.
We have three types of handlers in the chain:
-
MultipleofTwoHandler: checks if the number is a multiple of two -
MultipleofThreeHandler: checks if the number is a multiple of three -
...