<p>The <strong>chain of responsibility pattern</strong> comes first under<strong><a href="https://dineshonjava.com/behavioral-design-pattern/"> behavioral patterns</a> </strong>in object-oriented programming. The design pattern consists of processing objects and command objects. The processing objects feature the logic that defines what type of command objects, it can process. The ones that are not defined in that processing object, are passed to the others in the chain.</p>
<h2>The Chain of Responsibility Pattern</h2>
<div style="text-align: left;">
<blockquote><p><strong>According to the Gang of Four:</strong></p>
<div style="text-align: left;">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.</div>
</blockquote>
</div>
<p>In the standard chain of responsibility model variant, some processing object may act as ‘dispatchers’, which means, they are able to send the command out in different directions. This forms a ‘tree of responsibility’. There are some cases, where this process runs recursively. The processing object would be calling higher-up processing objects with command in order to solve a smaller part of the problem. This recursion tends to continue until either the command is processed or the whole responsibility tree is explored.</p>
<div style="background-color: #f2f9fc; border-radius: 3px; border: 1px solid #c9e6f2; line-height: 1.45; padding: 16px;">
<h2 dir="ltr">Spring 5 Design Pattern Book</h2>
<div dir="ltr" style="color: #20124d; font-family: 'calibri' , sans-serif; font-size: 13pt; text-align: justify;">You could purchase my <strong>Spring 5 book</strong> that is with title name &#8220;<strong>Spring 5 Design Pattern</strong>&#8220;. This book is available on the <a href="https://www.amazon.in/Spring-Design-Patterns-Dinesh-Rajput/dp/1788299450/ref=sr_1_1?ie=UTF8&;qid=1507925340&;sr=8-1&;keywords=spring+5+design+pattern" target="_blank" rel="noopener"><strong>Amazon</strong></a> and <a href="https://www.packtpub.com/application-development/spring-5-design-patterns" target="_blank" rel="noopener"><strong>Packt</strong></a> publisher website. Learn various <strong>design patterns</strong> and <strong>best practices</strong> in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- &#8220;<strong>AUTHDIS40</strong>&#8220;.</div>
<div dir="ltr"></div>
<div dir="ltr"><a href="https://www.amazon.in/Spring-Design-Patterns-Dinesh-Rajput/dp/1788299450/ref=sr_1_1?s=books&;ie=UTF8&;qid=1512607966&;sr=1-1&;keywords=dinesh+rajput" target="_blank" rel="noopener"><img class="aligncenter wp-image-3053 size-medium" title="Spring-5-Design-Pattern" src="https://dineshonjava.com/wp-content/uploads/2013/03/Spring-5-design-pattern-243x300.jpg" width="243" height="300" /></a></div>
</div>
<p>To design, versatile and reusable object-oriented software, there are <a href="https://dineshonjava.com/design-patterns_25/"><strong>23 well-known design patterns</strong></a>, the chain of responsibility is one of them. The idea of the chain of responsibility is not to link the sender of the request and the receiver. This gives the opportunity to more than one object to carry out the command. Although, when the receiver is not capable of solving the problem, it sends the problem to another object of the tree. In real life, the vending machine is a suitable example which is easy to comprehend as well. When the buyer inserts the coin and presses the button for a particular item, the coin is passed from object to object until it reaches the one which was selected by the buyer.</p>
<div style="text-align: left;">
<blockquote><p><strong>also read:</strong></p>
<ul style="text-align: left;">
<li><a title="https://dineshonjava.com/observer-pattern-design-patterns-java/" href="https://dineshonjava.com/observer-pattern-design-patterns-java/">Observer Design Pattern</a></li>
<li><a title="https://dineshonjava.com/command-pattern-design-patterns-java/" href="https://dineshonjava.com/command-pattern-design-patterns-java/">Command Design Pattern</a></li>
<li><a title="https://dineshonjava.com/strategy-pattern-design-patterns-java/" href="https://dineshonjava.com/strategy-pattern-design-patterns-java/">Strategy Design Pattern</a></li>
<li><a title="https://dineshonjava.com/template-method-pattern-design-java/" href="https://dineshonjava.com/template-method-pattern-design-java/">Template method Design Pattern</a></li>
<li><a title="https://dineshonjava.com/interpreter-pattern-design-patterns-java/" href="https://dineshonjava.com/interpreter-pattern-design-patterns-java/">Interpreter Design Pattern</a></li>
<li><a title="https://dineshonjava.com/iterator-pattern-design-patterns-java/" href="https://dineshonjava.com/iterator-pattern-design-patterns-java/">Iterator Design Pattern</a></li>
<li><a title="https://dineshonjava.com/mediator-pattern-design-patterns-java/" href="https://dineshonjava.com/mediator-pattern-design-patterns-java/">Mediator Design Pattern</a></li>
<li><a title="https://dineshonjava.com/memento-pattern-design-patterns-java/" href="https://dineshonjava.com/memento-pattern-design-patterns-java/">Memento Design Pattern</a></li>
<li><a title="https://dineshonjava.com/creational-design-patterns/" href="https://dineshonjava.com/creational-design-patterns//">Creational GoF Design Patterns</a></li>
<li><a title="https://dineshonjava.com/structural-design-patterns/" href="https://dineshonjava.com/structural-design-patterns/">Structural GoF Design Patterns</a></li>
</ul>
</blockquote>
</div>
<h2>Benefits of Chain of Responsibility Pattern</h2>
<p>There are following benefits of this pattern.</p>
<ul>
<li>It reduces the coupling between sender and receiver objects in the system to handle a request.</li>
<li>It is more flexible to assign the responsibility to another referenced object.</li>
<li>This pattern makes a chains of objects using composition, and this set of objects work as a single unit.</li>
</ul>
<h2>UML Class Diagram for this pattern</h2>
<p>Let&#8217;s see the following UML diagram is showing the all components of chain of responsibility design pattern:</p>
<p><img class="aligncenter wp-image-3326 size-full" src="https://dineshonjava.com/wp-content/uploads/2017/12/chain.gif" alt="Chain of Responsibility Pattern" width="433" height="165" /></p>
<h3>Handler</h3>
<p>This is an abstract class or interface in the system to handle request.</p>
<h3>ConcreteHandler</h3>
<p>These are concrete classes, implement Handler to handle the request, or it passes same request to the next successor of the handler chain.</p>
<h3>Client</h3>
<p>It is main application class to initiate the request to the handlers objects on the chain.</p>
<p>The structure of the chain of responsibility is defined to have a Handler. The Handler is the object which defines the request or the problem. The other part is known as Concrete handlers, they are the receiver objects. The handler sends the problem to the first receiver object, if that object is unable to handle the request, it passes on that request to the successive receiver object that, it is linked to. The request is passed until it reaches to the receiving object which is able to solve that problem. The chain of responsibility reduces the complexities between objects’ interconnections. The sender (handler) of the request only need to have the reference to the receiver object which is at the head of the chain and each receiver object need to have the reference to the successive receiver object only.</p>
<h2>Example for Chain of Responsibility Design Pattern Implementation</h2>
<p>The chain of responsibility design pattern is designed for certain scenarios when they occur in an application. For example, when more than one object is capable of handling the request and it does not have to be a particular object and with the handler determined at run-time, multiple objects must be able to handle the request.</p>
<p>The design enables the sender to generate a request and pass it on the tree without having to know which object is capable of handling the request. The chain of responsibility can be designed in different languages. For example, Java, C#, crystal, and python.</p>
<p>This real-world code demonstrates the Chain of Responsibility pattern in which several linked managers and executives can respond to a purchase request or hand it off to a superior. Each position has can have its own set of rules which orders they can approve.</p>
<h3>Step 1: Create an abstract Approver class.<br />
Approver.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.behavior.chainofresp; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public abstract class Approver { 
	 
	protected Approver successor; 
 
	public void setSuccessor(Approver successor){ 
		this.successor = successor; 
 } 
 
	public abstract void processRequest(Purchase purchase); 
	 
} 
 
</pre>
<h3>Step 2: Create concrete classes extending the approver class.<br />
Director.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.behavior.chainofresp; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class Director extends Approver { 
 
	@Override 
	public void processRequest(Purchase purchase) { 
		if(purchase.get_amount() <; 10000.0){ 
			System.out.println(this.getClass().getSimpleName()+" approved request #"+ purchase.get_number()); 
		}else if (successor != null){ 
			successor.processRequest(purchase); 
		} 
	} 
} 
 
</pre>
<h3>VicePresident.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.behavior.chainofresp; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class VicePresident extends Approver { 
 
	@Override 
	public void processRequest(Purchase purchase) { 
		if(purchase.get_amount() <; 25000.0){ 
			System.out.println(this.getClass().getSimpleName()+" approved request #"+ purchase.get_number()); 
		}else if (successor != null){ 
			successor.processRequest(purchase); 
		} 
	} 
 
} 
 
</pre>
<h3>President.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.behavior.chainofresp; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class President extends Approver { 
 
	@Override 
	public void processRequest(Purchase purchase) { 
		if(purchase.get_amount() <; 100000.0){ 
			System.out.println(this.getClass().getSimpleName()+" approved request #"+ purchase.get_number()); 
		}else { 
			System.out.println("Request #"+purchase.get_number()+" requires an executive meeting!"); 
		} 
	} 
 
} 
 
</pre>
<h3>Step 3: Create a demo class.</h3>
<p>Create different types of approvers. Assign them limit of amount of a purchase and if purchase limit beyond the approver right then he delegates to higher level approver. Next approver in each approver represents the part of the chain.</p>
<h3>ChainPatternDemo.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.behavior.chainofresp; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class ChainPatternDemo { 
 
	/** 
	 * @param args 
	 */ 
	public static void main(String[] args) { 
	 
		// Setup Chain of Responsibility 
		Approver dinesh = new Director(); 
		Approver arnav = new VicePresident(); 
		Approver anamika = new President(); 
 
		dinesh.setSuccessor(arnav); 
		arnav.setSuccessor(anamika); 
 
		// Generate and process purchase requests 
		Purchase purchase = new Purchase(1000, 3050.00, "Library Books"); 
		dinesh.processRequest(purchase); 
 
		purchase = new Purchase(1001, 30500.10, "Lab Machines"); 
		dinesh.processRequest(purchase); 
 
		purchase = new Purchase(1002, 130500.00, "Apple Mac Books"); 
		dinesh.processRequest(purchase); 
	} 
 
} 
 
</pre>
<h3>Step 4: Let&#8217;s run this demo class and verify the output.</h3>
<pre class="highlight">Director approved request #1000 
President approved request #1001 
Request #1002 requires an executive meeting! 
 
</pre>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/template-method-pattern-design-java/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/visitor-pattern/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '3322'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…