设计模式-行为型-责任链模式

1、定义

责任链模式:将请求的发送者和接受者解耦,使得多个对象都有处理这个请求的机会

写法

public interface InvokerHandler {

    //汇报工作
    void requestPermission(InvokerHandler handler);
    //处理核心逻辑
    void handleRequest(int limit);
    //当前权限
    int hasLimit();
    //当前职位
    String hasJob();

}

/**
 * 责任链
 */
public abstract class Leader implements InvokerHandler{

    private InvokerHandler nextHandler;

    @Override
    public void requestPermission(InvokerHandler handler) {
        this.nextHandler = handler;
    }

    @Override
    public void handleRequest(int limit) {

        if (limit <= hasLimit()){
            System.out.println(hasJob()+"拥有权限" +limit+"额度,审批");
        }else{
            if(nextHandler == null){
                System.out.println("没有上级汇报对象");
            }else {
                nextHandler.handleRequest( limit );
            }
        }

    }

}

public class Boss extends Leader {

    @Override
    public int hasLimit() {
        return Integer.MAX_VALUE;
    }

    @Override
    public String hasJob() {
        return "老板";
    }
}

public class Director extends Leader{

    @Override
    public int hasLimit() {
        return 5000;
    }

    @Override
    public String hasJob() {
        return "主管";
    }
}

public class Group extends Leader{

    @Override
    public int hasLimit() {
        return 3000;
    }

    @Override
    public String hasJob() {
        return "组员";
    }
}

//经理
public class Manager extends Leader {

    @Override
    public int hasLimit() {
        return 10000;
    }

    @Override
    public String hasJob() {
        return "经理";
    }
}

/**
 * 责任链模式
 */
public class TestMain {

    public static void main(String[] args){

        Boss boss = new Boss();
        Manager manager = new Manager();
        Director director = new Director();
        Group group = new Group();

        //确定汇报关系
        group.requestPermission( director );
        director.requestPermission( manager );
        manager.requestPermission( boss );
        boss.requestPermission( null );


        //组员汇报
        group.handleRequest( 2000 );

        //主管处理
        director.handleRequest( 300 );

        //经理处理
        manager.handleRequest( 20000 );

        //老板处理
        boss.handleRequest( 100 );
        boss.handleRequest( 1000 );
        boss.handleRequest( 900000 );

    }
}

代码示例

https://github.com/yinlingchaoliu/23-design-pattern

你可能感兴趣的:(设计模式-行为型-责任链模式)