或许你已经看惯了javabean和层叠构造.
/**
* Builder模式
* @author Macrotea
*
*/
public class ManFacts {
private String name;
private int age;
private double height;
private double weight;
public static class Builder {
// 必须
private String name;
private int age;
// 可选
private double height;
private double weight;
public Builder(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Builder height(double height) {
this.height = height;
return this;
}
public Builder weight(double weight) {
this.weight = weight;
return this;
}
public ManFacts build() {
return new ManFacts(this);
}
}
private ManFacts(Builder builder) {
this.age = builder.age;
this.name = builder.name;
this.height = builder.height;
this.weight = builder.weight;
}
}
public static void main(String[] args) {
ManFacts manFacts=new ManFacts.Builder("macrotea", 22).height(180).weight(140).build();
}