Chain of Responsibility design pattern — with examples
Tags: chainofresponsibility, softwaredesignpattern, designpatterns
Published: 2020-08-31 09:39:37

---
title: Chain of Responsibility design pattern — with examples
published: true
date: 2020-08-31 09:22:29 UTC
tags: chainofresponsibility,softwaredesignpattern,designpatterns
canonical_url: https://angrynerds.co/blog/chain-of-responsibility-design-pattern-with-examples/
---

Design patterns are not difficult to learn, but mastering them takes time. Still, it’s absolutely worth it! Knowledge on design patterns is necessary when you want to grow as a professional developer and build better software.

![](https://cdn-images-1.medium.com/max/1024/1*kCWv2eAivV-ndavn3nhc3w.jpeg)

Design patterns can be divided into three groups: **creational, structural, and behavioral.** Chain of Responsibility belongs to the behavioral one — which is a group of design patterns that help with better interaction between objects in your code.


> **TIP:** There is a classic book discussing this topic and describing 23 design patterns — “Design Patterns: Elements of Reusable Object-Oriented Software”. You should definitely read it if you are not familiar with the matter.


![](https://cdn-images-1.medium.com/max/568/0*ATCmdG7psYeOGRbx.jpg)


### Let’s learn more about the Chain of Responsibility with some practical examples

The Chain of Responsibility pattern is used to replace statements like _if … else if … else_ with a more object-oriented form. Let’s consider calculating a tax amount that is different for each country. The first version of the method handling this calculation could look like this:

{% gist https://gist.github.com/angrynerds-marcin/5a7ae52dccd9469086dd3e0a7e2d5f6e.js %}

It does not look that complicated, but the code can easily become longer and more laborious with time. In the next version, the tax may be calculated differently for various types of products, we may also have more countries that we want to calculate tax for. Moreover, at some point in the future, the law may be changed and that will result in different formulas based on date. This is a perfect example to use the Chain of Responsibility pattern. Take a look at the tax calculation problem implemented with this pattern:

{% gist https://gist.github.com/angrynerds-marcin/786b79f41fe3db7433f96ffb17cc342e.js %}

In this version, we don’t have five _if_ statements in one method and each type of tax is calculated by its own class. That way our code follows the Single Responsibility Principle, which is **one of the most important rules in clean coding**. To use these new classes, we have to create an instance of each class and set value for Next property. See an example here:

{% gist https://gist.github.com/angrynerds-marcin/404309e81f5e68a14aa48d7f35f339fd.js %}

If you had trouble with understanding how it works, I recommend you set a breakpoint and use a debugger to check which instructions are executed. ​

Here is another example — an algorithm that recommends you the next video to watch based on your age. This is a really simple example because it always returns the same video, but it fits nicely into the Chain of Responsibility pattern.

{% gist https://gist.github.com/angrynerds-marcin/3dd10dda361c43b576a6980d3654556b.js %}

And the third example — it’s the code for an ATM that checks if it can dispense cash using a finite number of notes inside the machine. In this case, we will have just one implementation of an abstract class, but we will define a chain consisting of three links using that one class.

{% gist https://gist.github.com/angrynerds-marcin/9e3571ba29bf891d7d13ae4846fa05ec.js %}

Here is how we can use it:

{% gist https://gist.github.com/angrynerds-marcin/d3943e64c22ba097da86c04de8858585.js %}

By now, I think you have already grasped the concept of the Chain of Responsibility pattern. Here is a class diagram and a sequence diagram that presents it:

![](https://cdn-images-1.medium.com/max/700/0*QozH-jjN9lhSxlTA.jpg)

### Chain of Responsibility vs other patterns

#### Chain of Responsibility vs Decorator

The Chain of Responsibility design pattern may appear similar to the Decorator design pattern but the key difference is that the former can be stopped at any part of the processing, and the latter executes all steps (assuming that passed data was valid and it didn’t throw an exception). Decorator adds something with each step. ​

#### Chain of Responsibility vs Strategy

With the Chain of Responsibility pattern, each object is responsible for executing an action on the next object, whereas, with the Strategy pattern, the client of that code has to decide which implementation should be used. ​

### What next?

I strongly recommend you to read the book mentioned in the intro: _Design Patterns: Elements of Reusable Object-Oriented Software_. You can also watch a [series of courses on Pluralsight](https://www.pluralsight.com/paths/design-patterns-in-c) in the design patterns path. There is also a fun experiment that you can check out on GitHub: [FizzBuzz Enterprise Edition](https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition) is a no-nonsense implementation of FizzBuzz made by serious businessmen for serious business purposes.

### Feel free to share your thoughts or questions in the comments!

_Article by Marcin Zarębski. Originally published at_ [_https://angrynerds.co_](https://angrynerds.co/blog/chain-of-responsibility-design-pattern-with-examples/)_._