职责链模式
文章目录
- 职责链模式
- 什么是职责链模式
- 通过示例了解职责链模式
什么是职责链模式
职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止
通过示例了解职责链模式
职责链模式(Chain of Responsibility Pattern)是一种行为设计模式,它允许将请求沿着处理者对象的链式结构传递,直到某个对象处理它。下面是一个简单的Java职责链模式示例,用于处理不同级别的员工请假申请:
抽象处理者:员工接口
public interface Employee {void setNext(Employee employee);void processLeaveRequest(Integer leaveDays);
}
具体处理者:普通员工
public class RegularEmployee implements Employee {private Employee next;@Overridepublic void setNext(Employee employee) {this.next = employee;}@Overridepublic void processLeaveRequest(Integer leaveDays) {if (leaveDays <= 3) {System.out.println("Regular employee approved 3 days or less leave.");} else if (next != null) {System.out.println("Regular employee forwarded the request to higher authority.");next.processLeaveRequest(leaveDays);} else {System.out.println("Leave request exceeds regular employee's limit.");}}
}
具体处理者:主管
public class Manager implements Employee {private Employee next;@Overridepublic void setNext(Employee employee) {this.next = employee;}@Overridepublic void processLeaveRequest(Integer leaveDays) {if (leaveDays <= 7) {System.out.println("Manager approved 7 days or less leave.");} else if (next != null) {System.out.println("Manager forwarded the request to higher authority.");next.processLeaveRequest(leaveDays);} else {System.out.println("Leave request exceeds manager's limit.");}}
}
具体处理者:部门经理
public class DepartmentHead implements Employee {@Overridepublic void setNext(Employee employee) {// 不需要设置下一个处理者,因为部门经理是最高级别的审批人}@Overridepublic void processLeaveRequest(Integer leaveDays) {if (leaveDays <= 14) {System.out.println("Department head approved 14 days or less leave.");} else {System.out.println("Leave request exceeds department head's limit.");}}
}
主程序
public class ChainOfResponsibilityDemo {public static void main(String[] args) {Employee regular = new RegularEmployee();Employee manager = new Manager();Employee departmentHead = new DepartmentHead();regular.setNext(manager);manager.setNext(departmentHead);regular.processLeaveRequest(5); // 输出:Regular employee approved 3 days or less leave.regular.processLeaveRequest(8); // 输出:Regular employee forwarded the request to higher authority. Manager approved 7 days or less leave.regular.processLeaveRequest(16); // 输出:Regular employee forwarded the request to higher authority. Manager forwarded the request to higher authority. Leave request exceeds department head's limit.}
}
- Employee接口是抽象处理者,定义了设置下一个处理者和处理请假申请的方法。
- RegularEmployee, Manager, 和 DepartmentHead是具体处理者,实现了Employee接口,并根据各自的权限范围处理请假申请。
- 职责链的建立是通过setNext方法将处理者对象链接在一起。
- main方法展示了如何创建职责链,并通过processLeaveRequest方法处理不同数量的请假天数请求。
职责链模式允许在不增加额外的复杂性的情况下添加新的处理者,同时保持了请求的发送者和接收者的解耦。