职责连模式:
使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系,将多个对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。
// 管理者
public abstract class Manager {
// 当前管理者的上级
private Manager superior;
public Manager getSuperior() {
return superior;
}
public void setSuperior(Manager superior) {
this.superior = superior;
}
// 处理员工请求
public abstract void handleRequest(Request req);
}
// 经理
public class CommonMannager extends Manager {
@Override
public void handleRequest(Request req) {
if (req.getType().equals("leave") && req.getNum() <= 2) {
System.out.println("CommonManager: I agree the leave request");
} else {
System.out.println("CommonManager: I has no right to handle it, Pls ask help from Majordemo!");
// 申请转到上级处理
this.getSuperior().handleRequest(req);
}
}
}
// 总监
public class Majordemo extends Manager {
@Override
public void handleRequest(Request req) {
if (req.getType().equals("leave") && req.getNum() <= 5) {
System.out.println("Majordemo: I agree the leave request");
} else {
System.out.println("Majordemo: I has no right to handle it, Pls ask help from GereralManager!");
// 申请转到上级处理
this.getSuperior().handleRequest(req);
}
}
}
// 总经理
public class GeneralManager extends Manager {
@Override
public void handleRequest(Request req) {
if (req.getType().equals("leave")) {
System.out.println("GereralManager: I agree the leave request");
} else if (req.getType().equals("increase salary") && req.getNum() <= 1000) {
System.out.println("GereralManager: I agree the salary increase request");
} else {
System.out.println("GereralManager: pls request next time");
}
}
}
// 申请者
public class Request {
// 申请类别
private String type;
// 申请内容
private String content;
// 申请数量
private int num;
public Request(String type, int num) {
this.type = type;
this.num = num;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
// 客户端
public class ChainOfResponsibilityMain {
public static void main(String[] args) {
Manager commonManager = new CommonMannager();
Manager majordemo = new Majordemo();
Manager generalManager = new GeneralManager();
// 设置自己的上级
commonManager.setSuperior(majordemo);
majordemo.setSuperior(generalManager);
// 设置员工请求内容
Request req1 = new Request("leave", 3);
Request req2 = new Request("increase salary", 2000);
// 经理接受请求
commonManager.handleRequest(req1);
commonManager.handleRequest(req2);
}
}
职责链的好处:
1. 职责链可以简化对象的相互连接,它们仅需保持一个指向其后继者的引用,而不需要保持它所有候选接受者的引用。
2. 由于是客户端来定义链的结构,我们可以随时地增加或修改处理一个请求的结构,增加了给对象指派职责的灵活性。