Design Pattern Download: The Chain Of Responsibility Pattern
The Chain of Responsibility pattern is a Behavioral Pattern used in software engineering when we want to enable our programs to accept different kinds of requests and respond to them in different ways, executing a sequence of handlers depending on the request. You can think of it as passing a baton one handler “runner” does their job and then passes the request of to the next, if there is an error in the handler (the baton gets dropped) then no subsequent handlers are invoked.
Example
We are creating a meal ordering service and have several steps in creating an order. 1) authenticating 2) scheduling the delivery 3) processing payment. In the future, we may want to add additional steps like “1b) check if the restaurant can make the order” so we do not want to create one single handler which does all of these steps since that will make the code cluttered and difficult to change. We opt to create microservices for each step, but how do we tell these microservices how to interact? we could have some kind of event bus that the handlers all listen to, but wouldn’t it be so easy for the handler to just call the next handler directly and “pass the baton”? The Chain of responsibility will help us do just that!
When to use the Chain Of Responsibility ?
- When you want your microservices to execute in a specific order.
- When you want your workflow to take different paths depending on the request but do not know the complete set of processes that need to be done for different requests at the time, or if that list may grow.
What is the Chain Of Responsibility Pattern composed of?
- The handler interface ( an interface that all the handlers implement with a
handlerRequest
function) - The Handlers (the individual handlers for each microservice)
Implementation
The Interface
The Handlers
Base
Concrete
Now we can call the auth handler with our request and it will do its work and pass the request on to the next handler and so on until our order is complete. If any handler fails along the way the request will be dropped and no subsequent handler resources will be created.
Verifying request...
Scheduling order...
Processing Payment...