-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathBuilderPattern.java
More file actions
61 lines (51 loc) · 1.57 KB
/
BuilderPattern.java
File metadata and controls
61 lines (51 loc) · 1.57 KB
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
package JavaIsCool.BuilderPattern.builderpatternexample1;
public class Student {
private String regNo;
private String firstName;
private String lastName;
private double gpa;
public Student(Builder builder) {
this.regNo = builder.regNo;
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.gpa = builder.gpa;
}
static class Builder {
private String regNo;
private String firstName;
private String lastName;
private double gpa;
public Builder(String regNo) {
this.regNo = regNo;
}
public Builder firstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder lastName(String lastName) {
this.lastName = lastName;
return this;
}
public Builder gpa(double gpa) {
this.gpa = gpa;
return this;
}
public Student build() {
return new Student(this);
}
}
@Override
public String toString() {
return "Student{" +
"regNo='" + regNo + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", gpa=" + gpa +
'}';
}
public static void main(String[] args) {
Student.Builder studentBuilder = new Student.Builder("123456");
Student student = studentBuilder.firstName("John").lastName("Doe").gpa(3.5).build();
System.out.println(student);
}
}