刚刚开通了一个公众号,会分享一些技术博客和自己觉得比较好的项目,同时会更新一些自己使用的工具和图书资料,后面会整理一些面试资料进行分享,觉得有兴趣的可以关注一下。
项目场景:
工作中最近对接的第三方系统的API
,请求体是JSON
格式的,嵌套的层级真有够深的。但是变化的值就那几个,为了最深层的几个值得变化,得一层一层得构造值,太麻烦了。这个时候得建造者模式真堪大用!!
解决方案:
如下代码,其实嵌套了多层之后,变化得只有最深层得value
,所以可以直接新建一个Builder
,只要传最里面得属性值,直接帮你组建好整个流程。见Builder
部分。
@Data
public class AllRequest {
private Request request = new Request();
@Data
private static class Request{
private Property1 property1;
private Property2 property2;
}
@Data
private static class Property1 {
private List<ChildProperty> children;
}
@Data
private static class Property2{
private List<ChildProperty> children;
}
@Data
@AllArgsConstructor
private static class ChildProperty{
private String key;
private String value;
}
public static AllRequestBuilder builder() {
return new AllRequestBuilder();
}
public static class AllRequestBuilder {
private AllRequest allRequest = new AllRequest();
private AllRequestBuilder(){}
public AllRequestBuilder property1(@NonNull String ...values) {
Property1 property1 = allRequest.getRequest().getProperty1();
if (Objects.isNull(property1)) {
property1 = new Property1();
allRequest.getRequest().setProperty1(property1);
}
List<ChildProperty> children = property1.getChildren();
if (CollectionUtils.isEmpty(children)) {
children = new ArrayList<>();
property1.setChildren(children);
}
for (String value : values) {
children.add(new ChildProperty(key, value));
}
return this;
}
public MDPRequestBuilder property2(@NonNull String ...values) {
Property2 property2 = allRequest.getRequest().getProperty2();
if (Objects.isNull(property1)) {
property2 = new Property2();
allRequest.getRequest().setProperty2(property2);
}
List<ChildProperty> children = property2.getChildren();
if (CollectionUtils.isEmpty(children)) {
children = new ArrayList<>();
property21.setChildren(children);
}
for (String value : values) {
children.add(new ChildProperty(key, value));
}
return this;
}
public AllRequest build() {
return allRequest;
}
}
}