责任链模式

行为型模式

责任链模式

责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链,通常每个接收者都包含对另一个接收者的引用,如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者

优点

缺点

使用场景

示例


@Component
class ChainHandler1 implements BaseChainHandler {

    @Autowired
    private ChainHandler2 nextHandLer;

    @Override
    public List<Object> filter(handleObj obj) {
        List<Object> returnList = new ArrayList<>();
        for (Object o : obj.getItem()) {
            if (o.equals("test")) {
                returnList.add(o);
            }
        }

        return returnList;
    }

    @Override
    public void handle(handleObj obj) {
        List<Object> returnList = this.filter(obj);

        //todo handle returnList
        returnList.stream().forEach(o -> o.getClass());

        nextHandLer.handle(obj);
    }
}


@Component
class ChainHandler2 implements BaseChainHandler {

    @Override
    public List<Object> filter(handleObj obj) {
        List<Object> returnList = new ArrayList<>();
        for (Object o : obj.getItem()) {
            if (o.equals("test2")) {
                returnList.add(o);
            }
        }

        return returnList;
    }

    @Override
    public void handle(handleObj obj) {
        List<Object> returnList = this.filter(obj);

        //todo handle returnList
        returnList.stream().forEach(o -> o.getClass());

    }
}

interface BaseChainHandler {
    List<Object> filter(handleObj obj);

    void handle(handleObj obj);
}

class handleObj {
    List<Object> item;

    public List<Object> getItem() {
        return item;
    }

    public void setItem(List<Object> item) {
        this.item = item;
    }
}