Design Pattern | Chain of Responsibility

What Is the Chain of Responsibility Pattern?

  • Chain means a sequence, and Responsibility means responsibility. Chain of Responsibility therefore means a chain of responsibility. In practice, it is often easier to understand as a rotating or passing structure.
  • The Chain of Responsibility pattern connects several objects in a chain and walks through that chain in order to decide the final object that will handle a request.
  • If a request comes to someone and that person can handle it, they handle it. If they cannot, they pass the request to the next person. Repeating this process is the Chain of Responsibility pattern.
  • In GoF design patterns, it is classified as a behavioral design pattern.

Chain of Responsibility Pattern Example Program

The example program resolves an input problem through one of several support objects.

Class Diagram
Chain of Responsibility Pattern Class Diagram

The main roles are Trouble, which represents a problem, Support, which is the common support class, and concrete support classes such as no-support, limit-based support, odd-number support, and special-number support. Each support object decides whether it can solve the problem; if not, it forwards the problem to the next support object in the chain.

Advantages

This pattern separates the sender of a request from the object that handles it. A request can be passed along the chain until an appropriate handler is found, so handlers can be added, removed, or reordered without changing the requester.