java设计模式(五)责任链模式

  很多对象有每个对象对其下家的引用而连接起来形成一条链,请求在这条链上传递,直到链上某个对象决定处理此请求,应用场景如单位审批流程等。

  要点:1)抽象处理者角色:定义处理请求接口及设定下家引用

        2)具体处理着角色:具体处理请求或选择将请求传给下家

1、抽象处理者角色类,定义处理请求接口及下家引用

public abstract class PriceHandle {

    protected PriceHandle successor;

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

    public abstract void process(float discount);

    public static PriceHandle createPriceHandle() {
        PriceHandle sales = new Sales();
        PriceHandle direct = new Direct();
        PriceHandle ceo = new CEO();

        sales.setSuccessor(direct);
        direct.setSuccessor(ceo);
        return sales;
    }
}

2、具体处理者角色类销售类

public class Sales extends PriceHandle {
    public void process(float discount) {
        if(discount <= 0.1) {
            System.out.format("%s批准了折扣:%.2f%n",this.getClass().getName(), discount);
        } else {
            successor.process(discount);
        }
    }
}

3、具体处理者角色主管类

public class Direct extends PriceHandle {

    public void process(float discount) {
        if(discount <= 0.2) {
            System.out.format("%s批准了折扣:%.2f%n",this.getClass().getName(), discount);
        } else {
            successor.process(discount);
        }
    }
}

4、具体处理者角色ceo类

public class CEO extends PriceHandle {
    public void process(float discount) {
        if(discount <= 0.3) {
            System.out.format("%s批准了折扣:%.2f%n",this.getClass().getName(), discount);
        } else {
            System.out.format("%s拒绝了折扣:%.2f%n",this.getClass().getName(), discount);
        }
    }
}

5、测试类

public class Model {

    private PriceHandle priceHandle;

    public void setPriceHandle(PriceHandle priceHandle) {
        this.priceHandle = priceHandle;
    }

    public void requestDiscount(float discount) {
        priceHandle.process(discount);
    }

    public static void main(String[] args) {
        Model customer = new Model();
        customer.setPriceHandle(PriceHandle.createPriceHandle());
        Random random = new Random();
        for(int i = 0; i < 100; i++) {
            System.out.print(i + ":");
            customer.requestDiscount(random.nextFloat());
        }
    }

}

 

posted @ 2017-07-19 21:42  code.world  Views(180)  Comments(0Edit  收藏  举报