Chain of Responsibility Pattern

It is a behavioural pattern. To process the chain of requests (processing pipeline) this pattern is used. Also, when you want to decouple a request’s sender and receiver, and when you don’t want to specify handlers explicitly in your code this pattern can be used. With this pattern, each processing object in the chain is responsible for a certain type of command and the processing is done, it forwards the command to the next processor in the chain.

Example

We need to handle the HTTP request. So we can design it with the following.

Structure of classes
HTTP class
WebServer class

WebServer class use chains of objects such as Authenticator, Logger, and Compressor. So we need to create a handler class to create a pipeline for them.

Handler class

The handle class is used to create the pipeline for the authenticator, compressor, and logger.

Authenticator class
Logger class
Compressor class
Main class

This method can be used to decouple classes easily.

--

--