原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11407114.html
1.定义
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
2.结构图
Handler:定义职责的接口,通常在这里定义处理请求的方法,可以在这里实现后继链。
ConcreteHandler:实现职责的类,在这个类中,实现对在它职责范围内请求的处理,如果处理,就继续转发请求给后继者。
Client:职责链的客户端,向链上的具体处理对象提交请求,让职责链负责处理。
3.本质
职责链模式的本质:分离职责,动态组合。
4.Code Demo
Handler.java
package org.fool.dp.cor; public abstract class Handler {
protected Handler successor; public void setSuccessor(Handler successor) {
this.successor = successor;
} public abstract void handleRequest();
}
ConcreteHandler1.java
package org.fool.dp.cor; public class ConcreteHandler1 extends Handler {
@Override
public void handleRequest() {
boolean someCondition = false; if (someCondition) {
System.out.println("ConcreteHandler1 invoked...");
} else {
if (successor != null) {
successor.handleRequest();
}
}
}
}
ConcreteHandler2.java
package org.fool.dp.cor; public class ConcreteHandler2 extends Handler {
@Override
public void handleRequest() {
boolean someCondition = false; if (someCondition) {
System.out.println("ConcreteHandler2 invoked...");
} else {
if (successor != null) {
successor.handleRequest();
}
}
}
}
ConcreteHandler3.java
package org.fool.dp.cor; public class ConcreteHandler3 extends Handler {
@Override
public void handleRequest() {
boolean someCondition = true; if (someCondition) {
System.out.println("ConcreteHandler3 invoked...");
} else {
if (successor != null) {
successor.handleRequest();
}
}
}
}
Client.java
package org.fool.dp.cor; public class Client {
public static void main(String[] args) {
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handler3 = new ConcreteHandler3(); handler1.setSuccessor(handler2);
handler2.setSuccessor(handler3); handler1.handleRequest();
}
}