责任链模式(chain of responsibility):
将能够处理同一类请求的对象连成一条链,所提交的请求沿着链传递,链上的对象逐个判断是否有能力处理该请求,如果能则处理,如果不能则传递给链上的下一个对象
角色:
抽象处理者(Handler)
具体处理者(ConcreteHandler)
客户端(Client)
下面模拟请假来实现责任链模式
package designmode.chainofresponsibility;
public class LeaveRequest {
private String empName;
private int leaveDays;
private String reason; //请假原因
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getLeaveDays() {
return leaveDays;
}
public void setLeaveDays(int leaveDays) {
this.leaveDays = leaveDays;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public LeaveRequest(String empName, int leaveDays, String reason) {
super();
this.empName = empName;
this.leaveDays = leaveDays;
this.reason = reason;
}
}
package designmode.chainofresponsibility;
public abstract class Leader {
protected String name;
protected Leader nextLeader; //责任链上的后维对象
public Leader(String name) {
super();
this.name = name;
}
public void setNextLeader(Leader nextLeader) {
this.nextLeader = nextLeader;
}
public abstract void handleRequest(LeaveRequest request);
}
package designmode.chainofresponsibility;
/**
* 经理
* @author baiyi
*
*/
public class Manager extends Leader{
public Manager(String name) {
super(name);
}
@Override
public void handleRequest(LeaveRequest request) {
if(request.getLeaveDays()<10) {
System.out.println("经理审批通过!!");
}else {
if(this.nextLeader !=null) {
System.out.println("权限不够!需要总经理审批!!");
this.nextLeader.handleRequest(request);
}
}
}
}
package designmode.chainofresponsibility;
/**
* 总经理
* @author baiyi
*
*/
public class GeneralManager extends Leader{
public GeneralManager(String name) {
super(name);
}
@Override
public void handleRequest(LeaveRequest request) {
if(request.getLeaveDays()<30) {
System.out.println("审批通过!!");
}else {
System.out.println("审批不予通过");
}
}
}
package designmode.chainofresponsibility;
/**
* 主任
* @author baiyi
*
*/
public class Director extends Leader{
public Director(String name) {
super(name);
}
public void handleRequest(LeaveRequest request) {
if (request.getLeaveDays()<3) {
System.out.println("主任审批通过");
}else {
if(this.nextLeader != null) {
System.out.println("权限不够,需要经理审批!!");
this.nextLeader.handleRequest(request);
}
}
}
}
package designmode.chainofresponsibility;
public class Client {
public static void main(String [] args) {
Leader a = new Director("张三");
Leader b = new Manager("李四");
Leader c = new GeneralManager("王五");
//组织责任链对象的关系
a.setNextLeader(b);
b.setNextLeader(c);
LeaveRequest req = new LeaveRequest("TOM",20,"go to English");
a.handleRequest(req);
}
}
非链表方式实现职责链
通过集合,数组生成职责链更加实用,实际上,很多项目中每个具体的Handler并不是由开发团队定义的,而是项目上线后由外部单位追加的,所以使用链表方式定义COR链就很困难
java中的Filter过滤器就是使用数组的方式。