责任链模式(Chain of Responsibility)

责任链模式是对象的行为模式。使多个对象都有机会处理请求,从而避免请求的发送者和接受者直接的耦合关系。
public abstract class Handler {
    protected Handler successor;
    public abstract void handlerRequest(String condition);

    protected Handler getSuccessor() {
        return successor;
    }

    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }
}

public class ConcreteHandler1 extends Handler{
    @Override
    public void handlerRequest(String condition) {
        // TODO Auto-generated method stub
        // 如果是自己的责任,就自己处理,负责传给下家处理
        if(condition.equals("ConcreteHandler1")){
            System.out.println( "ConcreteHandler1 handled ");
            return ;
        }else{
            System.out.println( "ConcreteHandler1 passed ");
            getSuccessor().handlerRequest(condition);
        }
}

public class ConcreteHandler2 extends Handler{
    @Override
    public void handlerRequest(String condition) {
        // TODO Auto-generated method stub
        // 如果是自己的责任,就自己处理,负责传给下家处理
        if(condition.equals("ConcreteHandler2")){
            System.out.println( "ConcreteHandler2 handled ");
            return ;
        }else{
            System.out.println( "ConcreteHandler2 passed ");
            getSuccessor().handlerRequest(condition);
        }
    }
}

public class ConcreteHandlerN extends Handler{
    @Override
    public void handlerRequest(String condition) {
        // TODO Auto-generated method stub
        System.out.println( "ConcreteHandlerN handled");
    }
}

//测试
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handlern = new ConcreteHandlerN();
//链起来
handler1.setSuccessor(handler2);
handler2.setSuccessor(handlern);
//假设这个请求是ConcreteHandler2的责任
handler1.handlerRequest("ConcreteHandler2");

public static void main(String[] args) {
	// TODO Auto-generated method stub
	Handler handler1 = new ConcreteHandler1();
	Handler handler2 = new ConcreteHandler2();
	Handler handlern = new ConcreteHandlerN();		
	//链起来
	handler1.setSuccessor(handler2);
	handler2.setSuccessor(handlern);		
	//假设这个请求是ConcreteHandler2的责任
	handler1.handlerRequest("ConcreteHandler2");
}

你可能感兴趣的:(设计模式,责任链模式,java,开发语言)