或许你已经看惯了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();
}
本文介绍了一种使用Java实现的Builder模式,通过一个具体的例子展示了如何构造具有必填和可选属性的对象。这种方式不仅提高了代码的可读性,还使得创建复杂对象的过程更加清晰。

被折叠的 条评论
为什么被折叠?



