定义:向下传递事件的模式即责任链模式。

1、事件类拥有共同的父类Event。
2、事件处理的类都要共同实现一个事件接口方法,方法参数为共同的事件父类。
3、事件处理类中含有下一级的事件处理类实例字段,定义为接口类型;
4、事件处理类的接口方法中通过instanceof判断是否本类处理,如果不是调用下一级的事件类来处理。

核心:某个接口的实现类中有这个接口的另一个实现类属性(字段),if not, field do same thing (invoke the same method)。

public class Event {
}
public class OneDayRestEvent extends Event {
}
public class TwoDayRestEvent extends Event {
}
public class FiveDayRestEvent extends Event {
}
public interface EventHandler {
    void handle(Event event);
}
public class LeaderEventHandler implements EventHandler{
    private EventHandler eventHandler;
    public LeaderEventHandler(EventHandler eventHandler){
        this.eventHandler=eventHandler;
    }
    @Override
    public void handle(Event event) {
        if(event instanceof OneDayRestEvent){
            System.out.println("do leaderEvent");
        }else{
            eventHandler.handle(event);
        }
    }
}
public class ManagerEventHandler implements EventHandler {
    private EventHandler eventHandler;
    public ManagerEventHandler(EventHandler eventHandler){
        this.eventHandler=eventHandler;
    }
    @Override
    public void handle(Event event) {
        if(event instanceof TwoDayRestEvent){
            System.out.println("do managerEvent");
        }else{
            eventHandler.handle(event);
        }
    }
}
public class DirectorEventHandler implements EventHandler {

    @Override
    public void handle(Event event) {
        System.out.println("do directorEvent");
    }
}
public class Test {
    public static void main(String[] args) {
        FiveDayRestEvent fiveDayRestEvent=new FiveDayRestEvent();
        OneDayRestEvent oneDayRestEvent=new OneDayRestEvent();
        TwoDayRestEvent twoDayRestEvent=new TwoDayRestEvent();

        EventHandler directorEventHandler=new DirectorEventHandler();
        //在链条中经理向下传递给总监
        EventHandler managerEventHandler=new ManagerEventHandler(directorEventHandler);
        //在链条中主管向下传递给经理
        EventHandler leaderEventHandler=new LeaderEventHandler(managerEventHandler);

        leaderEventHandler.handle(oneDayRestEvent);
        leaderEventHandler.handle(twoDayRestEvent);
        leaderEventHandler.handle(fiveDayRestEvent);
        System.out.println("=====================");
        managerEventHandler.handle(twoDayRestEvent);
        managerEventHandler.handle(fiveDayRestEvent);
        System.out.println("=====================");
        directorEventHandler.handle(fiveDayRestEvent);
    }
}

例:一天假只需组长审批,两天到五天假经理审批,五天以上总监审批。
这只是一种理论上的模式,真正应用时还需要增加很多逻辑来控制业务上责任链规则,比如如何判断是否本类执行,可能是instanceof判断,也可能设计个审批层级,大于某个level,manager处理等。

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required

fifty seven − forty eight =