1.什么时候使用构建器(Builder)
通常我们只需要使用 new User()
就可以创建一个对象,那么为什么还需要使用构建器呢。
假设我们有这么一个类
1
2
3
4
5
6
7
|
public class User {
private int id;
private String name;
private String phone;
private String sex;
private String IDCard;
}
|
如果创建一个User对象只有id
和name
是必须的,其他参数可以选填,也可以用下面两种方法创建该对象
1.构造函数
1
2
3
4
5
6
7
8
9
10
11
12
|
public class User {
private int id;
private String name;
private String phone;
private String sex;
private String IDCard;
public User(int id, String name) {
this.id = id;
this.name = name;
}
}
|
User user = new User(1,"izumi");
就能创建一个对象。那这时如果想用三个、五个参数,就只能依次增加多个构造函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public User(int id, String name) {
this.id = id;
this.name = name;
}
public User(int id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}
public User(int id, String name, String phone, String sex, String IDCard) {
this.id = id;
this.name = name;
this.phone = phone;
this.sex = sex;
this.IDCard = IDCard;
}
|
这显然就有些不那么优雅
2.set方法
我们可以使用JavaBeans的set方法来实现多个参数赋值(这里为方便直接用了lombok)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String phone;
private String sex;
private String IDCard;
public User(int id, String name) {
this.id = id;
this.name = name;
}
}
|
1
2
3
|
User user = new User(1,"izumi");
user.setSex("男");
user.setPhone("xxxxx");
|
这种做法简单易懂,但存在一些缺陷
因为构造过程被分到了几个调用中,在构造过程中JavaBean可能处于不一致的状态。
—《Effective Java》
这时我们就可以尝试使用构建器(Builder)
2.怎样使用构建器
直接看示例代码
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
|
package pub.izumi.coolqs;
public class User {
private int id;
private String name;
private String phone;
private String sex;
private String IDCard;
public static class Builder {
private int id;
private String name;
private String phone;
private String sex;
private String IDCard;
public Builder(int id, String name) {
this.id = id;
this.name = name;
}
public Builder phone(String val) {
this.phone = val;
return this;
}
public Builder sex(String val) {
this.sex = val;
return this;
}
public Builder IDCard(String val) {
this.IDCard = val;
return this;
}
public User build() {
return new User(this);
}
}
private User(Builder builder) {
id = builder.id;
name = builder.name;
phone = builder.phone;
sex = builder.sex;
IDCard = builder.IDCard;
}
}
|
builder方法在设值之后返回其本身,以便于把调用形成链接。创建对象示例:
1
2
|
User user1 = new User.Builder(1, "izumi").build();
User user2 = new User.Builder(1, "izumi").sex("男").phone("**").build();
|