考虑使用构建器(二)

考虑使用构建器

这个比较好理解,能够解决多参数构造器的复杂性,相对于get和set的JavaBean来说也有线程安全性的优势,个人倾向于使用lombok的@Builder注解,注解虽好用,不过也需要了解下注解背后的一些原理。

先看一下我写的一个简单示例

1
2
3
4
5
6
7
8
9
10
11
12
13

public class {

private String name;

private int age;

public static void main(String[] args) {

Person p = Person.builder().age(15).build();

}
}

再看下官方的标准示例

1
2
3
4
5
6
7
8
9
10
11

import lombok.Builder;
import java.util.Set;


public class BuilderExample {
private String name;
private int age;
@Singular
private Set<String> occupations;
}

等效代码:

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
import java.util.Set;
class BuilderExample {
private String name;
private int age;
private Set<String> occupations;

BuilderExample(String name, int age, Set<String> occupations) {
this.na 大专栏  考虑使用构建器(二)me = name;
this.age = age;
this.occupations = occupations;
}

public static BuilderExampleBuilder builder() {
return new BuilderExampleBuilder();
}

public static class BuilderExampleBuilder {
private String name;
private int age;
private java.util.ArrayList<String> occupations;

BuilderExampleBuilder() {
}

public BuilderExampleBuilder name(String name) {
this.name = name;
return this;
}

public BuilderExampleBuilder age(int age) {
this.age = age;
return this;
}

public BuilderExampleBuilder occupation(String occupation) {
if (this.occupations == null) {
this.occupations = new java.util.ArrayList<String>();
}

this.occupations.add(occupation);
return this;
}

public BuilderExampleBuilder occupations(Collection<? extends String> occupations) {
if (this.occupations == null) {
this.occupations = new java.util.ArrayList<String>();
}

this.occupations.addAll(occupations);
return this;
}

public BuilderExampleBuilder clearOccupations() {
if (this.occupations != null) {
this.occupations.clear();
}

return this;
}

public BuilderExample build() {
// complicated switch statement to produce a compact properly sized immutable set omitted.
// go to https://projectlombok.org/features/Singular-snippet.html to see it.
Set<String> occupations = ...;
return new BuilderExample(name, age, occupations);
}

@java.lang.Override
public String toString() {
return "BuilderExample.BuilderExampleBuilder(name = " + this.name + ", age = " + this.age + ", occupations = " + this.occupations + ")";
}
}
}

原文地址:https://www.cnblogs.com/lijianming180/p/12247699.html