简介:Builder模式是一步一步创建一个复杂对象的创建型模式,它允许用户在不知道内部构建细节的情况下,可以更精细的控制对象的构造流程。该模式是为了将构建复杂对象的过程和它的部件解耦,使得构建过程和部件的表示隔离开来,两者之间的耦合度也降到最低。
定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
主要功能用来构建一个对象,根据不同的数据构建不同的复杂对象
构建一个Student对象
public class Student {
private String name;
private int age;
private String location;
public Student(String name, int age, String location) {
this.name = name;
this.age = age;
this.location = location;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Student{");
sb.append("name='").append(name).append('\'');
sb.append(", age=").append(age);
sb.append(", location='").append(location).append('\'');
sb.append('}');
return sb.toString();
}
public static final class Builder {
private String name;
private int age;
private String location;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public Student build() {
if (location == null) {
location = "初始化地址";
}
if(age==0){
age=15;
}
if(name==null){
name="无名氏";
}
return new Student(name, age, location);
}
}
}
public class BuildRunningResult {
public static void main(String args[]) {
Student student = new Student.Builder()
.setName("小马哥")
.setAge(18)
.build();
System.out.println("Build模式结果是="+student.toString());
Student noNameStudent = new Student.Builder().setAge(20).build();
System.out.println("Build模式无名字结果是="+noNameStudent.toString());
}
}
运行后的结果如下:
Build模式结果是=Student{name='小马哥', age=18, location='初始化地址'}
Build模式无名字结果是=Student{name='无名氏', age=20, location='初始化地址'}
通过Build模式构建Student对象,可以设置不同的参数,如果不设置,则根据Build默认值初始化;这样便于根据不同的情况构建不同的复杂对象。