前言
我只是记录一下Builder的使用,这里我不分析什么场景使用这个Builder以及它的优缺点,有兴趣的可以自行百度。
代码
以Person类为例。
package builder;
public class Person {
private String name;
private String sex;
private int age;
private float height;
private float weight;
// Builder
public static class Builder {
private String name;
private String sex;
private int age;
private float height;
private float weight;
public Builder(String name, String sex) {
this.name = name;
this.sex = sex;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Builder height(float height) {
this.height = height;
return this;
}
public Builder weight(float weight) {
this.weight = weight;
return this;
}
public Person build() {
return new Person(this);
}
}
public Person(Builder builder) {
name = builder.name;
sex = builder.sex;
age = builder.age;
height = builder.height;
weight = builder.weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
}
测试类代码
package builder;
public class Builder_Test {
public static void main(String[] args) {
builder_test1();
}
public static void builder_test1() {
Person.Builder builder = new Person.Builder("张三", "男");
Person person = builder.age(18).height(170.3f).weight(56.4f).build();
System.out.println("Person=" + person.getName());
}
}
输出结果
Person=张三
分析
N/A