Java通过Builder建造器实现链式操作
博客专区 > kunping 的博客 > 博客详情
Java通过Builder建造器实现链式操作
kunping 发表于9个月前
Java通过Builder建造器实现链式操作
  • 发表于 9个月前
  • 阅读 62
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 新注册用户 域名抢购1元起>>>   

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));
    }
}

 

标签: Builder
共有 人打赏支持
粉丝 4
博文 31
码字总数 17257
×
kunping
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: