Design Pattern Chain of responsibility

Luiz Gustavo De O. Costa
2 min readSep 8, 2019

--

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.

GOF — Chain of responsibility
Real scenario

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

ChainDiscount

Add an abstract to class to support some operations of concrete class

Add the implementation class for each kind of discount

FirstPurchase

BuyThreePayTwo

DiscountByVoucher

And finally a main method to execute them. By the way there are unit tests for them.

AppMain

Thank you by reaching the end of this tutorial, see you on next :).

Thanks,

Luiz

--

--

Luiz Gustavo De O. Costa
Luiz Gustavo De O. Costa

Written by Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices

No responses yet