Chain of Responsibility

Amalakanthan R
2 min readJun 6, 2021

The Responsibility Chain A design pattern that constructs a chain of receiver objects for a request is one of the Gang of Four design patterns.

"Avoid tying the sender of a request to its receiver by giving different objects a chance to handle the request," according to the Chain of Responsibility Pattern.

The intent of the Chain of Responsibility Design pattern are allowing more than one object to handle a request helps to avoid coupling the request’s sender and receiver , Requests that start and stop using a single processing pipeline with a large number of possible handlers and recursive traversal of an object-oriented linked list.

There is a stream of requests to be handled, as well as a potentially variable number of “handler” or “processing element” or “node” objects.

Clients should “launch and leave” their requests at the pipeline’s entrance, with the processing pieces encapsulated behind a “pipeline” abstraction.

The pattern connects the receiving objects and then transfers any request messages from one object to the next until it reaches an item that can handle it. The quantity and kind of handler objects aren’t known in advance; they can be dynamically modified. The chaining mechanism makes advantage of recursive composition to connect an infinite number of handlers.

Interconnections between objects are made easier by Chain of Responsibility. Instead of holding references to all prospective recipients, each sender and receiver maintain a single reference to the chain’s head, and each receiver maintains a single reference to its immediate successor in the chain.

Ascertain that there is a “safety net” in place to “catch” any requests that go unanswered.

When each request is only handled by one handler or when the client object knows which service object should handle the request, do not utilize Chain of Responsibility.

Structure of the Design Pattern

Client requests are handled by the derived classes. If the “current” object is unavailable or insufficient, it delegated to the base class, which then delegated to the “next” object, and so on.

Each request could be handled by a number of different handlers. The request can be forwarded down the chain indefinitely, as long as the last link avoids delegating to a “null next.”

--

--