Chain of Responsibility

Intent

  • Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.

  • Chain the receiving objects and pass the request along the chain until an object handles it.

Problem

  • How can coupling the sender of a request to it's receiver be avoided?

  • How can more than one object handle a request?

Solution

  • Define a chain of Handler objects having the responsibility to either handle a request or forward it to the next handler.

  • A class sends a request to a chain of handlers and doesn't know (is independent of) which handler handles the request.

Advantages

✅ You can control the order of request handling. ✅ Single Responsibility Principle: You can decouple classes that invoke operations from classes that perform operations. ✅ Open/Closed Principle: You can introduce new handlers into the app without breaking the existing client code.

Disadvantages

❌ Some requests may end up unhandled.

Last updated