Java通过Builder建造器实现链式操作

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class RequestBuilder {

    private static final String PROCCOD = "PROCCOD";
    private static final String INFBDY = "INFBDY";

    private final Map<Object, Object> root;
    private final List<Object> list;

    private RequestBuilder(String code, String argName) {
        root = newMap();
        list = new ArrayList<Object>();
        Map<Object, Object> tempMap = newMap();
        root.put(PROCCOD, code);
        root.put(INFBDY, tempMap);
        tempMap.put(argName, list);
    }

    public ParamBuilder start() {
        return new ParamBuilder(list);
    }

    public Map<Object, Object> build() {
        return root;
    }

    private <K, V> Map<K, V> newMap() {
        return new HashMap<K, V>();
    }

    public final class ParamBuilder {
        private Map<Object, Object> paramMap = newMap();

        private ParamBuilder(List<Object> list) {
            list.add(paramMap);
        }

        public <K, V> ParamBuilder addParam(K key, V value) {
            this.paramMap.put(key, value);
            return this;
        }

        public RequestBuilder end() {
            return RequestBuilder.this;
        }
    }

    public static RequestBuilder create(String code, String argName) {
        return new RequestBuilder(code, argName);
    }
}




 

public class BuilderTest {
    public static void main(String[] args) {
        Map map = RequestBuilder.create("IMB1", "IMB1X1")
                .start().addParam("hkp", "123").addParam("hello", 1).end()
                .start().addParam("1", "xx1").addParam("2", "xx2").addParam("3", "xx3").end()
                .build();
        Gson gson = new Gson();
        System.out.println(gson.toJson(map));
    }
}

 

转载于:https://my.oschina.net/u/3209870/blog/848039

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值