思想
建造者模式简单来说就是将对象的创建由构造函数交给第三方的一个类,由这个类去负责创建对象的时候各种参数管理,我们可以调用不同的方法去个性化的定义创建对象时候的属性,而不用去将所有属性组合的构造函数都写出来。
主要使用的地方就是创建对象的时候参数太多了,如果都写成构造函数会太复杂。用这种方法,我们只用对每个属性创建一个设置的函数就可以了,而不必写多个构造函数。
代码
public class Robot {
public static String ROBOT_TYPE_1 = "家政";
public static String ROBOT_TYPE_2 = "教育";
public static String ROBOT_TYPE_3 = "军事";
private String name;
private int height;
private String type;
public Robot(String name, int height, String type) {
this.name = name;
this.height = height;
this.type = type;
}
@Override
public String toString() {
return "Robot{" +
"name='" + name + '\'' +
", height=" + height +
", type='" + type + '\'' +
'}';
}
public static class Builder {
private String name = "";
private int height = 3;
private String type = ROBOT_TYPE_1;
public Builder() { }
public Builder(Robot robot) {
this.name = robot.name;
this.height = robot.height;
this.type = robot.type;
}
public Builder name(String v) {
name = v;
return this;
}
public Builder height(int height) {
this.height = height;
return this;
}
public Builder type(String type) {
this.type = type;
return this;
}
public Robot builder() {
return new Robot(name, height, type);
}
}
public class Test {
public static void main(String[] args) {
Robot robot = new Robot.Builder()
.height(2)
.name("李四")
.type(Robot.ROBOT_TYPE_2)
.builder();
System.out.println(robot);
}
}
样例
使用builder的最常见的就是StringBuilder
,安卓中对于建造者模式的使用更加的常见,我的贴出来的这个东西就是模仿的sdk源代码中的格式。