# 责任链模式

# 简介

行为型模式,将请求和处理解耦,请求者不用关心是谁处理了当前请求。

# 示例

public abstract class Handle {
    protected Handle next;

    public Handle next(Handle next) {
        this.next = next;
        return this;
    }

    public abstract void doSomeThing(String type);
}

public class ConcreteHandle_A extends Handle {
    @Override
    public void doSomeThing(String type) {
        if ("A".equalsIgnoreCase(type)) {
            System.out.println("request has handled by Handle_A");
        } else {
            next.doSomeThing(type);
        }
    }
}

public class ConcreteHandle_B extends Handle {
    @Override
    public void doSomeThing(String type) {
        if ("B".equalsIgnoreCase(type)) {
            System.out.println("request has handled by Handle_B");
        } else {
            next.doSomeThing(type);
        }
    }
}

public class ConcreteHandle_C extends Handle {
    @Override
    public void doSomeThing(String type) {
        if ("C".equalsIgnoreCase(type)) {
            System.out.println("request has handled by Handle_C");
        } else {
            next.doSomeThing(type);
        }
    }
}

# 调用

@Test
public void tt(){
    Handle handle_A = new ConcreteHandle_A();
    Handle handle_B = new ConcreteHandle_B();
    Handle handle_C = new ConcreteHandle_C();

    handle_A.next(handle_B);
    handle_B.next(handle_C);

    handle_A.doSomeThing("A");
    handle_A.doSomeThing("B");
    handle_A.doSomeThing("C");
}

# 调用简装

public final class HandleClient {
    public static Handle getHandle(){
        Handle handle_A = new ConcreteHandle_A();
        Handle handle_B = new ConcreteHandle_B();
        Handle handle_C = new ConcreteHandle_C();

        handle_A.next(handle_B);
        handle_B.next(handle_C);

        return handle_A;
    }
}

# 调用

@Test
public void tt2(){
    Handle handle = HandleClient.getHandle();

    handle.doSomeThing("A");
    handle.doSomeThing("B");
    handle.doSomeThing("C");
}

# 避免性能问题,增加最大节点数限制

public abstract class Handle {
    static int max_handles = 10;
    protected Handle next;

    public Handle next(Handle next) {
        this.next = next;
        if(max_handles == 0){
            throw new IllegalArgumentException("handle maximizing");
        }
        max_handles--;
        return this;
    }

    public abstract void doSomeThing(String type);
}