Skip to content

Commit 830e1a2

Browse files
committed
增加 Builder 模式 README.md
1 parent fc5f66c commit 830e1a2

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed

builder/README.md

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
# 创建者模式
2+
3+
## 用途
4+
5+
将一个复杂对象的构造与它分开,使得同样的构造过程可以产生不同的对象。
6+
7+
## 实例
8+
9+
假定需要生成一个虚拟的人物模型,人物主要包括几个简单的属性:姓名、年龄、国籍以及肤色。假如一个数据模型的拥有很多属性,如果单纯使用构造方法来实例化对象,势必会造成构造方法参数爆炸的问题,也可以称之为“反可伸缩构造方法模式”。代码的可读性和可靠性大大降低。此时,可以为这个对象创建的过程指定一个创建者,我们只需要向创建者描述该对象的一些具体细节,接下来的构造过程就统统交给创建者完成了。
10+
11+
一下是“反可伸缩构造方法模式”的一个实例:
12+
13+
```
14+
public Person(String name,Integer age,Nationality nationality,SkinColor skinColor...){...}
15+
```
16+
如果一直这样下去,随着属性的增多,构造方法的参数的数量也会变得越来越多,对于开发人员是非常头疼的。对属性的更改使得构造方法的维护难度增加了不少,这就是所谓的“反可伸缩构造方法模式”。
17+
18+
## 模式分析
19+
20+
**Person 类**
21+
22+
```
23+
public class Person {
24+
private final String name;
25+
private final Integer age;
26+
private final Nationality nationality;
27+
28+
public String getName() {
29+
return name;
30+
}
31+
32+
public Integer getAge() {
33+
return age;
34+
}
35+
36+
public Nationality getNationality() {
37+
return nationality;
38+
}
39+
40+
public SkinColor getSkinColor() {
41+
return skinColor;
42+
}
43+
44+
private final SkinColor skinColor;
45+
46+
public Person(Builder builder) {
47+
this.name = builder.name;
48+
this.age = builder.age;
49+
this.skinColor = builder.skinColor;
50+
this.nationality = builder.nationality;
51+
}
52+
}
53+
```
54+
**Person 类的创建者**
55+
56+
```
57+
public static class Builder {
58+
59+
private String name;
60+
private Integer age;
61+
private Nationality nationality;
62+
private SkinColor skinColor;
63+
64+
public Builder age(Integer age) {
65+
this.age = age;
66+
return this;
67+
}
68+
69+
public Builder name(String name) {
70+
if (null == name) {
71+
throw new IllegalArgumentException("人必须有名字!");
72+
}
73+
this.name = name;
74+
return this;
75+
}
76+
77+
public Builder nationality(Nationality nationality) {
78+
this.nationality = nationality;
79+
return this;
80+
}
81+
82+
public Builder skinColor(SkinColor skinColor) {
83+
this.skinColor = skinColor;
84+
return this;
85+
}
86+
87+
public Person build() {
88+
return new Person(this);
89+
}
90+
}
91+
```
92+
93+
**Person 类对象的构造过程**
94+
95+
```
96+
Person personWang = new Person.Builder()
97+
.name("小王")
98+
.age(25)
99+
.nationality(Nationality.CHINA)
100+
.skinColor(SkinColor.YELLOW)
101+
.build();
102+
```
103+
104+
## 适用场景
105+
106+
* 创建一个复杂对象的算法应该独立于组成对象的组成部分以及它们是如何组合的
107+
* 构建过程必须为所构造的对象提供不同的表示形式

0 commit comments

Comments
 (0)