Chain of Responsibility Design Pattern in Java
This article explains Chain of Responsibility design pattern in java with UML class diagram. It then takes an example scenario in java and explains it with class diagram and code.
Introduction Chain of Responsibility Design Pattern is a behavioral design pattern among the Gang Of Four(GOF)Article on GOF Patterns & their types Design Patterns. Being a behavioral design pattern, the Chain of Responsibility pattern deals with how objects of the designed system interact with each other. What is Chain of Responsibility Design Pattern Chain of Responsibility Pattern decouples the handler of a request from its sender by providing multiple potential handlers chained in a sequence. As the request reaches the first handler object, the object checks if it can handle this request. If yes, it handles the request, else it forwards the request to the next handler object in the chain. Note that this process of handling or forwarding is recursive in nature. The recursive nature of the pattern reflects in its self-referencing design. When to use Chain of Responsibility Design Pattern
Class Diagram for Chain of Responsibility Design Pattern
Explanation of Chain of Responsibility Design Pattern's Class Diagram
OUTPUT on running StudentComplaintSystem.java
Explanation of Java Example’s Class Diagram and Code
The Java class diagram above depicts Chain of Responsibility Design pattern implemented for a Student Complaint System. In this complaint system complaint request for students up to 4 past complaints is handled by the class teacher, between 5 to 9 past complaints is handled by the vice principal and more than 9 past complaints is handled by the principal.
Lets quickly go through whats there in Java's example's class diagram and corresponding code -
Summary
In the above tutorial we understood what is Chain of Responsibility design pattern and the main scenarios in which this pattern is applicable. We then looked at the UML class diagram for Chain of Responsibility Design Pattern & its explanation, a Java Use Case implementing the pattern with its class diagram and code for the classes shown in the class diagram, followed by explanation of both the class diagram & code. This concludes the tutorial on Chain of Responsibility design pattern.
Introduction Chain of Responsibility Design Pattern is a behavioral design pattern among the Gang Of Four(GOF)Article on GOF Patterns & their types Design Patterns. Being a behavioral design pattern, the Chain of Responsibility pattern deals with how objects of the designed system interact with each other. What is Chain of Responsibility Design Pattern Chain of Responsibility Pattern decouples the handler of a request from its sender by providing multiple potential handlers chained in a sequence. As the request reaches the first handler object, the object checks if it can handle this request. If yes, it handles the request, else it forwards the request to the next handler object in the chain. Note that this process of handling or forwarding is recursive in nature. The recursive nature of the pattern reflects in its self-referencing design. When to use Chain of Responsibility Design Pattern
- The handler of the request is to be determined dynamically: Which of the multiple handler objects will handle the request is not known in advance. It is determined at runtime.
- The handlers can be added dynamically: The potential handlers for the request can be added when the system is running. For example: In a hierarchical setup(like employee hierarchy in an organization) of handlers, the objects representing individual personnel at various levels in the hierarchy may not be available at system design time.
Handler
is the base class for all handlers.Handler
holds a self-referential association with itself to implement the recursive nature of handlers calling next handlers in chain.ConcreteHandler
instances extendHandler
and implement the actual logic of handling in thehandle()
method.Client
initiates the request which is handled by theConcreteHandler
objects in a sequential chain.
Code for the classes shown in Java Example’s Class Diagram
//ComplaintRequest.java
public class ComplaintRequest{
private int pastComplaintCount;
private String studentRollNo;
public ComplaintRequest(int pastComplaintCount, String studentRollNo) {
super();
this.pastComplaintCount = pastComplaintCount;
this.studentRollNo = studentRollNo;
}
//getter/setter for pastComplaintCount and studentRollNo
}
//Staff.java
public abstract class Staff{
protected Staff successor=null;
public Staff(Staff successor) {
super();
this.successor= successor;
}
public abstract void handleComplaint(ComplaintRequest complaintRequest);
}
//ClassTeacher.java
public class ClassTeacher extends Staff{
public ClassTeacher(Staff successor) {
super(successor);
}
@Override
public void handleComplaint(ComplaintRequest complaintRequest) {
if(complaintRequest.getPastComplaintCount()<=4){
System.out.println("ClassTeacher handled the complaint for roll no:"+ complaintRequest.getStudentRollNo());
}else{
successor.handleComplaint(complaintRequest);
}
}
}
//VicePrincipal.java
public class VicePrincipal extends Staff{
public VicePrincipal(Staff successor) {
super(successor);
}
@Override
public void handleComplaint(ComplaintRequest complaintRequest) {
if(complaintRequest.getPastComplaintCount()<=9){
System.out.println("VicePrincipal handled the complaint for roll no:"+ complaintRequest.getStudentRollNo());
}else{
successor.handleComplaint(complaintRequest);
}
}
}
//Principal.java
public class Principal extends Staff{
public Principal(Staff successor) {
super(successor);
}
@Override
public void handleComplaint(ComplaintRequest complaintRequest) {
System.out.println("Principal handled the complaint for roll no:"+complaintRequest.getStudentRollNo());
}
}
//StudentComplaintSystem.java
public class StudentComplaintSystem {
public static void main(String args[]){
//hierarchy of staff is created
ClassTeacher classTeacher=new ClassTeacher(new VicePrincipal(new Principal(null)));
//3 complaint requests are created and sent to class teacher
classTeacher.handleComplaint(new ComplaintRequest(3,"A101"));
classTeacher.handleComplaint(new ComplaintRequest(7,"B202"));
classTeacher.handleComplaint(new ComplaintRequest(10,"C303"));
}
}
ClassTeacher handled the complaint for roll no:A101 VicePrincipal handled the complaint for roll no:B202 Principal handled the complaint for roll no:C303
ComplaintRequest
encapsulates the student complaint raised.Staff
is the base abstract class for all handlers in the chain. It holds a reference to itself which is named as successor in terms of next in the chain for handling the request. In this case successor is nextStaff
object greater in authority. Authority structure is 'class teacher > vice principal > principal'.- All
ComplaintRequest
s are created an given to aClassTeacher
instance for handling. IfpastComplaintCount
is <=4 then class teacher handles the complaint else it passes the complaint to its successorVicePrincipal
’s object. VicePrincipal
handles complaints tillpastComplaintCount
is <=9. Complaints withpastComplaintCount
greater than 9 is given to thePrincipal
object to handle.- The output is shown for 3 complaint requests raised which are handled by class teacher, vice principal and principal.
Gang of Four (GOF) Design Patterns on JavaBrahman
Creational Patterns: Factory method PatternFactory Method Design Pattern in Java Builder PatternBuilder Design Pattern in Java Prototype PatternPrototype Design Pattern in Java
Behavioral Patterns: Chain of Responsibility PatternChain of Responsibility Design Pattern in Java Observer PatternObserver Design Pattern in Java Iterator PatternIterator Design Pattern in Java State PatternState Design Pattern in Java Memento PatternMemento Design Pattern in Java Visitor PatternVisitor Design Pattern in Java Strategy PatternStrategy Design Pattern in Java Template Method PatternTemplate Method Design Pattern in Java
Structural Patterns: Adapter PatternAdapter design pattern in Java Composite PatternComposite Design Pattern in Java Facade PatternFacade Design Pattern in Java Proxy Pattern Java Proxy Design Pattern in Java
Analysis of Patterns: Strategy vs State PatternStrategy Design Pattern versus State Design Pattern
Creational Patterns: Factory method PatternFactory Method Design Pattern in Java Builder PatternBuilder Design Pattern in Java Prototype PatternPrototype Design Pattern in Java
Behavioral Patterns: Chain of Responsibility PatternChain of Responsibility Design Pattern in Java Observer PatternObserver Design Pattern in Java Iterator PatternIterator Design Pattern in Java State PatternState Design Pattern in Java Memento PatternMemento Design Pattern in Java Visitor PatternVisitor Design Pattern in Java Strategy PatternStrategy Design Pattern in Java Template Method PatternTemplate Method Design Pattern in Java
Structural Patterns: Adapter PatternAdapter design pattern in Java Composite PatternComposite Design Pattern in Java Facade PatternFacade Design Pattern in Java Proxy Pattern Java Proxy Design Pattern in Java
Analysis of Patterns: Strategy vs State PatternStrategy Design Pattern versus State Design Pattern