java中的builder模式
import android.text.TextUtils; /** * Created by toothwind on 2017/7/19. * you can contact me at : toothwind@163.com. * All Rights Reserved */ public class Demo { //属性 private String age; private String height; private String salary; //构造 private Demo(Builder builder) { this.age = builder.age; this.height = builder.height; this.salary = builder.salary; } //对外方法 public String age() { return age; } //对外方法 public String height() { return height; } //对外方法 public String salary() { return salary; } public Builder newBuilder() { return new Builder(this); } @Override public String toString() { return "Demo{" + "age='" + age + '\'' + ", height='" + height + '\'' + ", salary='" + salary + '\'' + '}'; } public static class Builder { private String age; private String height; private String salary; public Builder() { this.age = "18"; } private Builder(Demo demo) { this.age = demo.age; this.height = demo.height; this.salary = demo.salary; } public Builder age(String age) throws Exception { if (TextUtils.isEmpty(age)) { throw new Exception("年龄不能为空"); } this.age = age; return this; } public Builder height(String height) throws Exception { if (TextUtils.isEmpty(height)) { throw new Exception("身高不能为空"); } this.height = height; return this; } public Builder salary(String salary) throws Exception { this.salary = salary; return this; } public Demo build() { return new Demo(this); } } }