Chain or Responsibility Demo

Interface:

package ChainOfResponsibiltyDemo; interface LeaveApprover { void setNextApprover(LeaveApprover nextApprover); void approveLeave(LeaveRequest leaveRequest); }

Classes:

package ChainOfResponsibiltyDemo; // LeaveRequest class class LeaveRequest { private int days; public LeaveRequest(int days) { this.days = days; } public int getDays() { return days; } }
package ChainOfResponsibiltyDemo; class TeamLead implements LeaveApprover { private LeaveApprover nextApprover; public void setNextApprover(LeaveApprover nextApprover) { this.nextApprover = nextApprover; } public void approveLeave(LeaveRequest leaveRequest) { if (leaveRequest.getDays() <= 5) { System.out.println("Leave approved by Team Lead"); } else if (nextApprover != null) { nextApprover.approveLeave(leaveRequest); } else { System.out.println("Leave rejected"); } } }

Driver

In this example, each handler (TeamLead, DepartmentManager, and HRManager) represents a level of authority in the leave approval process. Each handler implements the LeaveApprover interface and has a reference to the next approver in the chain.

When a leave request is submitted, it is passed to the first handler in the chain (teamLead). If the team lead has the authority to approve the leave (in this case, for up to 5 days), the leave is approved. Otherwise, the request is passed to the next handler (departmentManager). The process continues until an approver can handle the request, or the request is rejected if it reaches the end of the chain.

By using the Chain of Responsibility pattern, the leave approval process is structured, and the responsibility for approving a leave request is delegated from one handler to another. Each handler has the flexibility to approve or reject the request based on its own criteria. This pattern promotes loose coupling between the sender of the request and its receivers, allowing for easy modification or extension of the approval process.