建造者模式

发布 : 2018-12-03 浏览 :

介绍

将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示.

uml

建造者模式

常用代码

google guava

private static Cache<String, Optional<WalletCooperatorFunCode>> permissionCache = CacheBuilder.newBuilder()
.expireAfterWrite(3, TimeUnit.MINUTES).build();

elasticsearch


TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(
InetAddress.getByName(hostArray[0]), port));

BoolQueryBuilder builder = QueryBuilders.boolQuery()
.must(QueryBuilders.rangeQuery("@timestamp").from("2018-05-22T10:51:46.570Z").to("2018-05-22T11:51:46.570Z"))
.must(QueryBuilders.matchQuery("transId", "1526977796409"))
.must(QueryBuilders.matchQuery("mhtOrderNo", "mchId12345678901527078420001"));

SearchRequestBuilder search = client.prepareSearch(index).setQuery(builder);
SearchResponse response = search.execute().actionGet();

StringBuilder

StringBuilder stringBuilder = new StringBuilder();
for (String key : keyList) {
String value = jsonObject.getString(key);
if (StringUtils.isNotBlank(value)) {
stringBuilder.append(key).append("=").append(value).append("&");
}
}

Demo

@ToString
public class Connect {

private String requestMethod;
private int timeout;
private boolean useProxy;
private String address;

public Connect(ConnectBuilder builder) {
this.requestMethod = builder.requestMethod;
this.useProxy = builder.useProxy;
this.address = builder.address;
this.timeout = builder.timeout;
}

public static class ConnectBuilder {

private String requestMethod = "http";
private int timeout = 0;
private boolean useProxy = false;
private String address;

public ConnectBuilder buildRequestMethod(String requestMethod) {
this.requestMethod = requestMethod;
return this;
}

public ConnectBuilder buildTimeout(int timeout) {
this.timeout = timeout;
return this;
}

public ConnectBuilder buildUseProxy(boolean useProxy) {
this.useProxy = useProxy;
return this;
}

public ConnectBuilder buildAddress(String address) {
this.address = address;
return this;
}
}
}

测试:

public class BuilderTest {

public static void main(String[] args) {

Connect.ConnectBuilder builder = new Connect.ConnectBuilder()
.buildTimeout(1)
.buildRequestMethod("https")
.buildUseProxy(true)
.buildAddress("https://liuzhihang.com");

Connect connect = new Connect(builder);

System.out.println(connect.toString());
}
}

总结

  • 创建步骤进行简化, 部分属性可以进行默认赋值, 并且代码比较清晰, 控制创建过程
  • 每个builder独立 和其他的建造者没有影响
  • 内部比较复杂, 当内部有一定的顺序性时, 可以使用

本文作者 : liuzhihang
原文链接 : https://liuzhihang.com/2018/12/03/builder-mode.html
版权声明 : 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!

博客已萌萌哒运行(●'◡'●)ノ♥
Theme - BMW | Made With 💗 | Powered by GodBMW