职责链的本质:分离职责,动态组合
样例:
/**
* 定义职责对象的接口
*
*/
public abstract class Handler {
protected Handler successor;
/**
* 设置下一个处理请求对象
* @param successor
*/
public void setSuccessor(Handler successor) {
this.successor = successor;
}
/**
* 处理聚餐费用的申请
* @param user 申请人
* @param fee 申请的费用
* @return
*/
public abstract String handlerFeeRequest(String user, double fee);
}
/**
* 部门经理审批
*
*/
public class DepManager extends Handler {
@Override
public String handlerFeeRequest(String user, double fee) {
String str = "";
if(fee < 1000) {
if("Joe".equals(user)) {
str = "Department manager agreed " + user + "'s request, the fee is $" + fee;
} else {
str = "Department manager didn't agree " + user + "'s request.";
}
return str;
}
// more than $1000, next to others.
if(this.successor != null) {
return successor.handlerFeeRequest(user, fee);
}
return str;
}
}
/**
* 项目经理审批
*
*/
public class ProjectManager extends Handler {
@Override
public String handlerFeeRequest(String user, double fee) {
String str = "";
if(fee < 500) {
if("Joe".equals(user)) {
str = "Project manager agreed " + user + "'s request, the fee is $" + fee;
} else {
str = "Project manager didn't agree " + user + "'s request.";
}
return str;
}
// more than $500, next to others.
if(this.successor != null) {
return successor.handlerFeeRequest(user, fee);
}
return str;
}
}
/**
* 总经理审批
*
*/
public class GeneralManager extends Handler {
@Override
public String handlerFeeRequest(String user, double fee) {
String str = "";
if(fee >= 1000) {
if("Joe".equals(user)) {
str = "General manager agreed " + user + "'s request, the fee is $" + fee;
} else {
str = "General manager didn't agree " + user + "'s request.";
}
return str;
}
// next to others.
if(this.successor != null) {
return successor.handlerFeeRequest(user, fee);
}
return str;
}
}
public class Client {
public static void main(String[] args) {
Handler h1 = new ProjectManager();
Handler h2 = new DepManager();
Handler h3 = new GeneralManager();
h2.setSuccessor(h3);
h1.setSuccessor(h2);
String ret1 = h1.handlerFeeRequest("Joe", 300);
System.out.println(ret1);
String ret2 = h1.handlerFeeRequest("Yoyo", 300);
System.out.println(ret2);
String ret3 = h1.handlerFeeRequest("Joe", 800);
System.out.println(ret3);
String ret4 = h1.handlerFeeRequest("Yoyo", 800);
System.out.println(ret4);
String ret5 = h1.handlerFeeRequest("Joe", 1300);
System.out.println(ret5);
String ret6 = h1.handlerFeeRequest("Yoyo", 1300);
System.out.println(ret6);
}
}