Design Pattern Chain of responsibility
What is?
Second the book Head First Design Patterns, this behavioral pattern 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.
Where to use?
This pattern can be used in any system that requires a chain to handle the request and avoid coupling of if/else decisions for each new handle, i.e. shopping cart, supermarket etc.
How to use?
The picture in the Example section shows how the classes works. The main idea is isolate each rule/decision/etc by class, and this class be nested of “chain”.
Example
First let’s look at GOF and after see how I handle in this example. The diagrams were done using mermaid and hackmd.io.
*The model classes such as ShoppingCart/Item are available in github.
Now, the expected class and code got from IDE. The code also is available in github.
Create a function interface to have the handle request
Add an abstract to class to support some operations of concrete class
Add the implementation class for each kind of discount
BuyThreePayTwo
And finally a main method to execute them. By the way there are unit tests for them.
Thank you by reaching the end of this tutorial, see you on next :).
Thanks,
Luiz