java 模式之 Builder 模式

一、简介

  • 我所认为的 Builder 模式的作用就是为了分解创建复杂对象的过程,如果一个类的成员变量过多,我们要是通过构造函数创建这个类的对象的话,会显得比较臃肿,而且看起来很复杂的样子。我们正常情况下创建对象的过程如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Person {
private String name;
private int age;
private String sex;
private String work;
private int pay;
private int child;
private String hobby;
public Person(String name, int age, String sex, String work,
int pay, int child, String hobby) {
this.name = name;
this.age = age;
this.sex = sex;
this.work = work;
this.pay = pay;
this.child = child;
this.hobby = hobby;
}
}

这个类中七个成员变量,构造方法有七个参数,反正我看到的第一眼就感觉烦,参数太多,看的头晕!

二、使用 Builder 模式来创建对象

  • 完整的代码如下所示:
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
public class Person {
private String name;
private int age;
private String sex;
private String work;
private int pay;
private int child;
private String hobby;
private Person(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.sex = builder.sex;
this.work = builder.work;
this.pay = builder.pay;
this.child = builder.child;
this.hobby = builder.hobby;
}
public static class Builder{
private String name;
private int age;
private String sex;
private String work;
private int pay;
private int child;
private String hobby;
public Builder() {
this.name = null;
this.age = 0;
this.sex = null;
this.work = null;
this.pay = 0;
this.child = 0;
this.hobby = null;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Builder sex(String sex) {
this.sex = sex;
return this;
}
public Builder work(String work) {
this.work = work;
return this;
}
public Builder pay(int pay) {
this.pay = pay;
return this;
}
public Builder child(int child) {
this.child = child;
return this;
}
public Builder hobby(String hobby) {
this.hobby = hobby;
return this;
}
public Person build(){
return new Person(this);
}
}
}

分析:

  • 第一步,先创建一个静态内部类 Builder ,参数与外部类一致

  • 第二步,添加构造函数,设置成员变量的默认值,如果没有特殊的要求不设置也行,因为本身就有默认值。

  • 第三步,改造一系列的 setter 方法,返回值改为 Builder

  • 第四步,修改外部类的构造函数私有化,并且修改参数为 Builder

  • 第五步,添加外部类的一系列 Getter 方法,对外暴露获取成员变量数据的方法,如果不需要不添加也可以。

  • 第六步,添加 build 方法,返回 Person 对象!

创建对象的过程如下:

1
2
3
4
5
Person person = new Person.Builder()
.age(3)
.child(2)
.hobby("吃")
.build();

这样就把创建对象的过程分离开了,看着也清晰了,并且不用分顺序,好处多多!