使代码更简洁(三)---利用Builder Pattern为对象属性赋值

文章目录

以前写在segmentFault上的一篇文章,搬移到这里

有一个有很多属性的类,在为它的属性赋值时,通常有两种方式,使用构造函数和使用set方法。可是使用构造函数有时会忘了各个字段的顺序 ,直接使用set方法,又比较麻烦。所以同事提出可以使用方法链。

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
public class User {
private int id;
private String name;
private int age;
private int sex;
private int cityId;
private int buId;
private int roleId;
private String pinyinName;
public String getPinyinName() {
return pinyinName;
}
public void setPinyinName(String pinyinName) {
this.pinyinName = pinyinName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public int getBuId() {
return buId;
}
public void setBuId(int buId) {
this.buId = buId;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(int id, String name, int age, int sex, int cityId, int buId,
int roleId, String pinyinName) {
super();
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
this.cityId = cityId;
this.buId = buId;
this.roleId = roleId;
this.pinyinName = pinyinName;
}
}

类似于StringBuilder的append方法

1
2
String s = new StringBuilder().append("0").append(1)
.append(" 2 ").append(3).toString();

让bean的每个属性的set方法都返回一个对象本身的引用,将User类的set方法改写成下面的样子:

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
public User setId(int id) {
this.id = id;
return this;
}
public User setName(String name) {
this.name = name;
return this;
}
public User setAge(int age) {
this.age = age;
return this;
}
public User setSex(int sex) {
this.sex = sex;
return this;
}
public User setCityId(int cityId) {
this.cityId = cityId;
return this;
}
public User setBuId(int buId) {
this.buId = buId;
return this;
}
public User setRoleId(int roleId) {
this.roleId = roleId;
return this;
}
public User setPinyinName(String pinyinName) {
this.pinyinName = pinyinName;
return this;
}

这样在对User的属性赋值时就简洁了许多。

1
2
3
4
5
6
7
User user = new User().setId(1).setAge(18)
.setBuId(127)
.setRoleId(12)
.setName("giraffe")
.setCityId(12)
.setSex(1)
.setPinyinName("gif");

大部分IDE默认生成无返回值的setter,不过Idea也支持生成返回this对象的方式。在生成setter时把template由default改为builder。如下图:
default setter

builder setter

不过不知道这样写会不会有什么不好的地方~~

分享到 评论