1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| class User { // 下面是“一堆”的属性 private String name; private String password; private String nickName; private int age;
// 构造方法私有化,不然客户端就会直接调用构造方法了 private User(String name, String password, String nickName, int age) { this.name = name; this.password = password; this.nickName = nickName; this.age = age; } // 静态方法,用于生成一个 Builder,这个不一定要有,不过写这个方法是一个很好的习惯, // 有些代码要求别人写 new User.UserBuilder().a()...build() 看上去就没那么好 public static UserBuilder builder() { return new UserBuilder(); }
public static class UserBuilder { // 下面是和 User 一模一样的一堆属性 private String name; private String password; private String nickName; private int age;
private UserBuilder() { }
// 链式调用设置各个属性值,返回 this,即 UserBuilder public UserBuilder name(String name) { this.name = name; return this; }
public UserBuilder password(String password) { this.password = password; return this; }
public UserBuilder nickName(String nickName) { this.nickName = nickName; return this; }
public UserBuilder age(int age) { this.age = age; return this; }
// build() 方法负责将 UserBuilder 中设置好的属性“复制”到 User 中。 // 当然,可以在 “复制” 之前做点检验 public User build() { if (name == null || password == null) { throw new RuntimeException("用户名和密码必填"); } if (age <= 0 || age >= 150) { throw new RuntimeException("年龄不合法"); } // 还可以做赋予”默认值“的功能 if (nickName == null) { nickName = name; } return new User(name, password, nickName, age); } } }
//调用 public class APP { public static void main(String[] args) { User d = User.builder() .name("foo") .password("pAss12345") .age(25) .build(); } }
|