-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuilder.java
More file actions
84 lines (70 loc) · 2.4 KB
/
Builder.java
File metadata and controls
84 lines (70 loc) · 2.4 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package DesignPatterns;
import java.time.LocalDate;
public class Builder {
public static void main(String[] args) {
Employee employee = Employee.builder()
.withAge(29)
.withName("Samael Smith")
.withUserName("sam@1234")
.withAddress("NYC, New York")
.build();
System.out.printf("Employee obj: %s", employee);
}
}
record Employee(
String name,
String userName,
String address,
int age,
String dateOfBirth) {
public static EmployeeBuilder builder() {
return new EmployeeBuilder();
}
public static class EmployeeBuilder {
private static final String DEFAULT_NAME = "Default Name";
private static final String DEFAULT_USERNAME = "default-user-name";
private static final String DEFAULT_ADDRESS = "127.0.0.1";
private static final int DEFAULT_AGE = 35;
private static final String DEFAULT_DOB = LocalDate.now().toString();
private String name;
private String userName;
private String address;
private int age;
private String dateOfBirth;
EmployeeBuilder() {
this.name = DEFAULT_NAME;
this.userName = DEFAULT_USERNAME;
this.address = DEFAULT_ADDRESS;
this.age = DEFAULT_AGE;
this.dateOfBirth = DEFAULT_DOB;
}
public EmployeeBuilder withName(String name) {
this.name = name;
return this;
}
public EmployeeBuilder withUserName(String userName) {
this.userName = userName;
return this;
}
public EmployeeBuilder withAge(int age) {
this.age = age;
return this;
}
public EmployeeBuilder withAddress(String address) {
this.address = address;
return this;
}
public EmployeeBuilder withDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
return this;
}
public Employee build() {
return new Employee(this.name, this.userName, this.address, this.age, this.dateOfBirth);
}
}
@Override
public String toString() {
return String.format("Employee{name='%s', userName='%s', address='%s', age=%d, dateOfBirth='%s'}",
name, userName, address, age, dateOfBirth);
}
}