责任链模式是对象的行为模式。使多个对象都有机会处理请求,从而避免请求的发送者和接受者直接的耦合关系。
public abstract class Handler {
protected Handler successor;
public abstract void handlerRequest(String condition);
protected Handler getSuccessor() {
public void setSuccessor(Handler successor) {
this.successor = successor;
public class ConcreteHandler1 extends Handler{
public void handlerRequest(String condition) {
if(condition.equals("ConcreteHandler1")){
System.out.println( "ConcreteHandler1 handled ");
System.out.println( "ConcreteHandler1 passed ");
getSuccessor().handlerRequest(condition);
public class ConcreteHandler2 extends Handler{
public void handlerRequest(String condition) {
if(condition.equals("ConcreteHandler2")){
System.out.println( "ConcreteHandler2 handled ");
System.out.println( "ConcreteHandler2 passed ");
getSuccessor().handlerRequest(condition);
public class ConcreteHandlerN extends Handler{
public void handlerRequest(String condition) {
System.out.println( "ConcreteHandlerN handled");
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handlern = new ConcreteHandlerN();
handler1.setSuccessor(handler2);
handler2.setSuccessor(handlern);
handler1.handlerRequest("ConcreteHandler2");
public static void main(String[] args) {
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handlern = new ConcreteHandlerN();
handler1.setSuccessor(handler2);
handler2.setSuccessor(handlern);
handler1.handlerRequest("ConcreteHandler2");