建造者模式

2020-11-08

java

外观往往和事物的本身完全不符,世人都容易为表面的装饰所欺骗。——《威尼斯商人》

这两天开发中用到了建造者模式,写起来感觉挺爽的

以前我们创建一个javabean

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
/**
* 自定义pojo
*/
public static class Teacher {
private String name;
private Integer age;

@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}

然后给它赋值

1
2
3
4
Teacher teacher = new Teacher();
teacher.setName("achao");
teacher.setAge(91);
System.out.println(teacher);

image-20201108133117805

建造者模式的话,写起来就要像这样

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
/**
* 自定义pojo
*/
public static class Student {
private String name;
private Integer age;

public Student() {
}

private Student(Student student) {
this.name = student.name;
this.age = student.age;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}

private static Builder builder() {
return new Builder();
}

public static class Builder {
private Student student;

public Builder() {
this.student = new Student();
}

public Student build() {
return new Student(this.student);
}

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

public Builder age(Integer age) {
this.student.age = age;
return this;
}

}

用起来就是这样

1
2
Student ruben = Student.builder().name("ruben").age(19).build();
System.out.println(ruben);

image-20201108133241535

那么,每次这么写肯定受不了,于是我们可以使用lombok

只需要在我们的javabean上加个@Builder注解就可以使用建造者模式了

image-20201108133510269

通过查看编译后的class文件可以看到Lombok和我们写的差不多,只不过它用的是全参构造

image-20201108133810645

仿照他的写出来就是这样的

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
/**
* 自定义pojo
*/
public static class Student {
private String name;
private Integer age;

Student(String name, Integer age) {
this.name = name;
this.age = age;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}

private static StudentBuilder builder() {
return new StudentBuilder();
}

public static class StudentBuilder {
private String name;
private Integer age;

StudentBuilder() {
}

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

public StudentBuilder age(Integer age) {
this.age = age;
return this;
}

public Student build() {
return new Student(name, age);
}

@Override
public String toString() {
return "StudentBuilder{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

}