Java Builder 模式,你搞明白了么?


Java Builder 模式,你搞明白了么?

 https://zhuanlan.zhihu.com/p/80910560

 
 1 public class Student {
 2 
 3     private String name;
 4 
 5     private int age;
 6 
 7     private int num;
 8 
 9     private String email;
10 
11     // 提供一个静态builder方法
12     public static Student.Builder builder() {
13         return new Student.Builder();
14     }
15     // 外部调用builder类的属性接口进行设值。
16     public static class Builder{
17         private String name;
18 
19         private int age;
20 
21         private int num;
22 
23         private String email;
24 
25         public Builder name(String name) {
26             this.name = name;
27             return this;
28         }
29 
30         public Builder age(int age) {
31             this.age = age;
32             return this;
33         }
34 
35         public Builder num(int num) {
36             this.num = num;
37             return this;
38         }
39 
40         public Builder email(String email) {
41             this.email = email;
42             return this;
43         }
44 
45         public Student build() {
46             // 将builder对象传入到学生构造函数
47             return new Student(this);
48         }
49     }
50     // 私有化构造器
51     private Student(Builder builder) {
52         name = builder.name;
53         age = builder.age;
54         num = builder.num;
55         email = builder.email;
56     }
57 
58     @Override
59     public String toString() {
60         return "Student{" +
61                 "name='" + name + '\'' +
62                 ", age=" + age +
63                 ", num=" + num +
64                 ", email='" + email + '\'' +
65                 '}';
66     }
67 }