Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:
See bookChain of Responsability
Behavioral patternThe Chain of Responsibility pattern stands out from others because of its versatility, allowing us to solve problems where we’re not sure which object should process a specific request; this design pattern can easily solve problems inheritance can’t because of its chain structure, where a series of objects try to process a request in sequence.
The components included in the pattern are:
- Client: User or system triggering the execution of the pattern.
- AbstractHandler: Base class used for defining the structure of every ConcreteHandler. This class is an aggregation of itself, which allows it to contain another AbstractHandler for carrying on with the execution chain.
- ConcreteHandler: It represents the concrete implementation of an AbstractHandler.
- The client sends a request to the chain of responsibility for its processing.
- The first Handler tries to process the request but it’s unable to do it, therefore, it relays the request to the next handler .
- The second Handler tries to process the request but it’s unable to do it, therefore, it relays the request to the next Handler .
- The third Handler tries to process the request but it’s unable to do it, therefore, it relays the request to the next Handler .
- The HandlerN (Any handler in the chain) is the one finally succeeding in processing the request, after which it sends a response (optional) so it can be relayed by all the previous Handlers until it reaches to the Client.
Real-world example
By implementing the Chain of Responsability design pattern, we are going to implement an order validation system. When we work with ERP or CRM systems, it's fairly common to manage almost everything through orders, being sales, purchases, services and installations. These orders are highly complex objects compounded by a lot of other objects, such as customers, providers, products, etcerera. These systems must check the completion of an order, and that all of the information they carry is valid to the type of order being processed. To that end, we will use the Chain of Responsability pattern and create an effective mechanism for validating any type of order, by reusing validators between these different types.