在我们日常研发中,建造者模式是使用的很多的一种模式。其实很多时候我们在不知不觉中就使用了别人设计的建造者模式而从中受益。比如Gson、okHttp、Retrift。如下代码:
Gson gson = new GsonBuilder()
.registerTypeAdapter(String.class,new StringAdapter())
.registerTypeAdapter(Integer.class,new IntegerAdapter())
.registerTypeAdapter(int.class,new IntegerAdapter())
.create();
先通过Builder然后在设置一些想要设置的参数,最后通过create()得到需要的对象。比起我们通常使用的构造函数、setter等的设置其好处是链式调用,欲设置的参数清晰,返回对象时机明确。
那我们也可以参考这种设计来设计我们自己类为建造者模式进行建造。
设计一个Student类如下:
public class Student {
private final String name;
private final String age;
private final String phone;
private final String address;
private Student(Builder builder){
this.name = builder.name;
this.address = builder.address;
this.age = builder.age;
this.phone = builder.phone;
}
public String getName() {
return name;
}
public static class Builder{
private final String name;
private final String age;
private String phone;
private String address;
public Builder(String name,String age){
this.name = name;
this.age = age;
}
public Builder setPhone(String phone){
this.phone = phone;
return this;
}
public Builder setAddress(String address){
this.address = address;
return this;
}
public Student build(){
Student student = new Student(this);
if(student.getName().equals("calm")){
throw new IllegalStateException("calm是非法用户");
}
return student;
}
}
@Override
public String toString() {
return "name = "+name+" age = "+age+" phone = "+phone+" address = "+address;
}
}
核心思想在内部的静态Bulider类,我们将建造的时候必须的参数放在Builder的构造函数中,非必须参数通过链式调用进行设置。最后通过build()方法返回Student对象。build()方法调用Student的私有构造函数,这个构造函数接收Builder作为参数。需要注意的是,如果要对返回对象的参数做合法化验证的话,一定要先构建对象在进行验证。因为在构建的过程中,是非线程安全的,意味着如果没构建之前去检测的话,可能会被别的线程更改掉检测的参数而失去了检测的意义。
最后附上调用的代码:
Student student = new Student.Builder("Calm","33")
.setAddress("China")
.setPhone("19999999999")
.build();
仅以此记录建造者模式的使用方式。