本文仅供学习交流使用,侵权必删。
不作商业用途,转载请注明出处
WHAT 什么是建造者
建造者模式(builder),将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。建造者主要用于创建一些复杂的对象,这些对象内部的构建通常是非常复杂的过程。
WHY 为什么使用建造者
- 如果一个类具有非常多属性,为了避免构造函数的参数列表太长,影响可读性。
- 建造者的好处是对象的创建代码和对象本身的代码解耦,调用者无需关心复杂的构建过程。提高代码的易用性
- 建造者能让用户使用到的是一个构造完整的对象,用户不会调用到一个未构造完整的对象。
HOW 建造者的实现(JAVA)
场景:创建一个资源配置对象,内部可能存在复杂的构造过程
- 资源配置类和建造器
package builderDesignPattern;
public class ResourceConfig {
private String url;
private String pwd;
private String user;
private int coreSize;
private int maxSize;
private ResourceConfig() {
}
public ResourceConfig(String url, String user, String pwd, int coreSize, int maxSize) {
this.url = url;
this.user = user;
this.pwd = pwd;
this.coreSize = coreSize;
this.maxSize = maxSize;
}
@Override
public String toString() {
return "ResourceConfig{" +
"url='" + url + '\'' +
", pwd='" + pwd + '\'' +
", user='" + user + '\'' +
", coreSize=" + coreSize +
", maxSize=" + maxSize +
'}';
}
public static class ResourceConfigBuilder {
private String url;
private String pwd;
private String user;
private int coreSize;
private int maxSize;
public ResourceConfigBuilder setUrl(String url) {
this.url = url;
return this;
}
public ResourceConfigBuilder setPwd(String pwd) {
this.pwd = pwd;
return this;
}
public ResourceConfigBuilder setUser(String user) {
this.user = user;
return this;
}
public ResourceConfigBuilder setCoreSize(int coreSize) {
this.coreSize = coreSize;
return this;
}
public ResourceConfigBuilder setMaxSize(int maxSize) {
this.maxSize = maxSize;
return this;
}
public ResourceConfig build() {
if (isEmpty(url)) {
throw new IllegalArgumentException();
}
if (isEmpty(user)) {
throw new IllegalArgumentException();
}
if (isEmpty(pwd)) {
throw new IllegalArgumentException();
}
if (coreSize > maxSize || coreSize <= Integer.MIN_VALUE) {
throw new IllegalArgumentException();
}
if (coreSize > maxSize || maxSize >= Integer.MAX_VALUE) {
throw new IllegalArgumentException();
}
return new ResourceConfig(url, user, pwd, coreSize, maxSize);
}
private boolean isEmpty(String s) {
return s == null || s.isEmpty();
}
}
}
- 客户端
public class BuilderClient {
public static void main(String[] args) {
String url = "https://www.xxoo.com";
String user = "admin";
String pwd = "a123";
ResourceConfig resourceConfig = new ResourceConfig.ResourceConfigBuilder().setCoreSize(1)
.setMaxSize(5).setUrl(url).setUser(user).setPwd(pwd).build();
System.out.println(resourceConfig.toString());
}
}