java 建造者模式
- 应用场景
- 一个类中构造器必传参数比较多,导致代码可读性比较差,容易出现bug
- 一个类创建后,不需要再次修改属性的值
- 建造者模式特点
- 通过build()函数创建基本类,通过set 方式给构造函数赋值
- 当构造函数参数比较多时,通过build() 和 set() 方法实现,代码结构逻辑清晰,代码精简
- 代码展示: 代码实现了一个资源池创建
public class ResourcePoolConfig {
private String poolName;
private Integer maxTotal;
private Integer maxIdle;
private Integer minIdle;
private ResourcePoolConfig(Builder builder) {
this.poolName = builder.getPoolName();
this.maxTotal = builder.getMaxTotal();
this.maxIdle = builder.getMaxIdle();
this.minIdle = builder.getMinIdle();
}
public String getPoolName() {
return poolName;
}
public Integer getMaxTotal() {
return maxTotal;
}
public Integer getMaxIdle() {
return maxIdle;
}
public Integer getMinIdle() {
return minIdle;
}
public static class Builder {
private final static int DEFAULT_MAX_TOTAL = 100;
private final static int DEFAULT_MAX_IDLE = 10;
private final static int DEFAULT_MIN_IDLE = 5;
private String poolName;
private int maxTotal = DEFAULT_MAX_TOTAL;
private int maxIdle = DEFAULT_MAX_IDLE;
private int minIdle = DEFAULT_MIN_IDLE;
public ResourcePoolConfig build() {
return new ResourcePoolConfig(this);
}
public String getPoolName() {
return poolName;
}
public Builder setPoolName(String poolName) {
this.poolName = poolName;
return this;
}
public Integer getMaxTotal() {
return maxTotal;
}
public Builder setMaxTotal(Integer maxTotal) {
this.maxTotal = maxTotal;
return this;
}
public Integer getMaxIdle() {
return maxIdle;
}
public Builder setMaxIdle(Integer maxIdle) {
this.maxIdle = maxIdle;
return this;
}
public Integer getMinIdle() {
return minIdle;
}
public Builder setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
return this;
}
}
}
/**
* 测试类
**/
public class Test {
public static void main(String[] args) {
ResourcePoolConfig config =
new ResourcePoolConfig.Builder().setMaxIdle(15).setPoolName("mysql1").setMaxTotal(100).build();
System.out.println(config.getMaxIdle());
System.out.println(config.getPoolName());
System.out.println(config.getMaxTotal());
}
}
如果描述不全,请评论区指出,卤煮尽快更改,感谢!