设计模式:责任链模式-chain of responsibility

职责链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理他为止。

设计模式:责任链模式-chain of responsibility_第1张图片
设计模式:责任链模式-chain of responsibility_第2张图片

优点:

 降低耦合:对象无需知道它的处理请求将被谁处理,只需要发送请求即可

 增强处理的灵活性:可以随意增删和改变请求的处理顺序 

缺点:

 效率较低;请求不一定都会被处理 

代码

Main

public class Main {

    public static void main(String[] args) {
        /**
         * absFactory Main
        DoorFactory ldf=new LeftDoorFactory();
        DoorFactory rdf=new RightDoorFactory();

        CarDoor audiLeftDoor=ldf.getAUDIDoor();
        audiLeftDoor.getColor();
        audiLeftDoor.getDir();

        CarDoor bmwRightDoor=rdf.getBMWDoor();
        bmwRightDoor.getColor();
        bmwRightDoor.getDir();

        DoorFactory bdf=new BackDoorFactory();
        CarDoor bmwBackDoor=bdf.getBMWDoor();
        bmwBackDoor.getColor();
        bmwBackDoor.getDir();
        */

        Handler h1=new FirstTax();
        Handler h2=new SecTax();
        h1.setSuccessor(h2);

        h1.doSomething(20000);
    }

}

abs:Handler

public abstract class Handler {

    protected Handler successor;

    public Handler getSuccessor() {
        return successor;
    }

    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }
    public abstract void doSomething(float sum);
}

imp:FirstTax

public class FirstTax extends Handler{

    @Override
    public void doSomething(float sum) {
        System.out.println("扣税3%");
        sum=(float)(sum*0.97);
        if(getSuccessor()!=null){
            getSuccessor().doSomething(sum);
        }else{
            System.out.println("sum is "+sum);
            System.out.println("结束");
        }
    }

}

imp:SecTax

public class SecTax extends Handler {

    @Override
    public void doSomething(float sum) {
        System.out.println("扣税5%");
        sum=(float)(sum*0.95);
        if(getSuccessor()!=null){
            getSuccessor().doSomething(sum);
        }else{
            System.out.println("sum is "+sum);
            System.out.println("结束");
        }
    }

}

你可能感兴趣的:(设计模式)