一、作用
避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。职责链模式是一种对象行为型模式。
二、例子
class PurchaseRequest {
private String purpose; //采购目的
public PurchaseRequest(String purpose) {
this.purpose = purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public String getPurpose() {
return this.purpose;
}
}
abstract class Approver {
protected Approver successor; //定义后继对象
protected String name; //审批者姓名
public Approver(String name) {
this.name = name;
}
//设置后继者
public void setSuccessor(Approver successor) {
this.successor = successor;
}
//抽象请求处理方法
public abstract void processRequest(PurchaseRequest request);
}
class Director extends Approver {
public Director(String name) {
super(name);
}
//具体请求处理方法
public void processRequest(PurchaseRequest request) {
if (request.getPurpose() < 50000) {
System.out.println("Director:"+name); //处理请求
}
else {
this.successor.processRequest(request); //转发请求
}
}
}
class VicePresident extends Approver {
public VicePresident(String name) {
super(name);
}
//具体请求处理方法
public void processRequest(PurchaseRequest request) {
if (request.getPurpose() < 100000) {
System.out.println("VicePresident:"+name);
}
else {
this.successor.processRequest(request); //转发请求
}
}
}