-
Notifications
You must be signed in to change notification settings - Fork 1
/
RecursiveGenerics.java
57 lines (47 loc) · 1.18 KB
/
RecursiveGenerics.java
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
// Fluent Builder Inheritance with Recursive Generics
package creational.builder;
class Person {
public String name;
public String position;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", position='" + position + '\'' +
'}';
}
}
class PersonBuilder<SELF extends PersonBuilder<SELF>> {
protected Person person = new Person();
public SELF withName(String name) {
person.name = name;
return self();
}
public Person build() {
return person;
}
protected SELF self() {
return (SELF) this;
}
}
class EmployeeBuilder
extends PersonBuilder<EmployeeBuilder> {
public EmployeeBuilder worksAt(String position) {
person.position = position;
return self();
}
@Override
protected EmployeeBuilder self() {
return this;
}
}
class FluentDemo {
public static void main(String[] args) {
EmployeeBuilder pb = new EmployeeBuilder();
Person igor = pb
.withName("Igor")
.worksAt("Developer")
.build();
System.out.println(igor);
}
}