Apache Commons Chain(1) -开源责任链模式(apache commons chain)


首先看官方介绍:

A popular technique for organizing the execution of complex processing flows is the "Chain of Responsibility" pattern

很受欢迎的(流行的)对于复杂的流程处理方式,也就是通常说的,责任链设计模式了。

下面我们来个简单的使用:

1、首先加入依赖


    commons-chain
    commons-chain
    1.2

To check for the most recent version of this library– go here.

2、首先我们就以我们最熟悉的业务场景,也是大多数demo 中使用到的

对于一个销售人员来说,要完成一个完整的销售过程,一般要遵循如下过程:

Apache Commons Chain(1) -开源责任链模式(apache commons chain)

这么一个过程 ,明显是一个流程处理的过程,怎么来代码实现呢?

或者如果实现了,又需要加入新的流程来了,怎么办呢?

怎么做到灵活实现兼容变更呢?

Apache common chain 就实现了这一责任链模式。

先来定义各个流程实现:

//获取客户信息
public class GetUserInfo implements Command {

    public boolean execute(Context context) throws Exception {
        System.out.println("Get user info begin");
        context.put("userName", "Tom");
        return false;
    }
}
//预约试驾
public class TestDriver implements Command {

    public boolean execute(Context context) throws Exception {
        System.out.println("Test driver begin....");
        return false;
    }
}
//谈判
public class NegotiateSale implements Command {

    public boolean execute(Context context) throws Exception {
        System.out.println("This is Negotiate");
        return false;
    }
}
//支付
public class ArrangeFinancing implements Command {

    public boolean execute(Context context) throws Exception {
        System.out.println("This is arranging financing");
        return false;
    }
}
//交付
public class CloseSale implements Command {

    public boolean execute(Context context) throws Exception {
        System.out.println("Thanks," + context.get("userName") + ",enjoying your driving");
        return false;
    }
}

OK 这里,流程就全部定义好了,这里可以看到,我们都实现了一个Command接口,来定义我们具体的业务实现,并且有个 全局Context ,用来保存后续需要处理的参数传递。

好了,怎么串起来整个流程呢?

public class CommondChain extends ChainBase {

    public CommondChain() {
        super();
        addCommand(new GetUserInfo());
        addCommand(new TestDriver());
        addCommand(new NegotiateSale());
        addCommand(new ArrangeFinancing());
        addCommand(new CloseSale());
    }

    public static void main(String[] args) {
        CommondChain commondChain = new CommondChain();
        Context context = new ContextBase();

        try {
            commondChain.execute(context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

可以 run 起来了 哈哈哈,输入结果:

Get user info begin
Test driver begin....
This is Negotiate
This is arranging financing
Thanks,Tom,enjoying your driving



展开阅读全文

页面更新:2024-06-13

标签:模式   责任   看官   全局   场景   灵活   接口   也就是   定义   流程   完整   参数   过程   客户   业务   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top