-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathbuilder1.java
50 lines (44 loc) · 1.28 KB
/
builder1.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
package builder;
public interface builder1 {
record Spaceship(String name, String captain, int torpedoes, int length) {}
class SpaceshipBuilder {
private String name;
private String captain;
private int torpedoes = -1;
private int length = -1;
public SpaceshipBuilder name(String name) {
this.name = name;
return this;
}
public SpaceshipBuilder captain(String captain) {
this.captain = captain;
return this;
}
public SpaceshipBuilder torpedoes(int torpedoes) {
this.torpedoes = torpedoes;
return this;
}
public SpaceshipBuilder length(int length) {
this.length = length;
return this;
}
public Spaceship build() {
if (name == null || captain == null || torpedoes == -1 || length == -1) {
throw new IllegalStateException("name, captain, torpedoes or length not initialized");
}
return new Spaceship(name, captain, torpedoes, length);
}
}
static void printSpaceship(Spaceship spaceship) {
System.out.println(spaceship);
}
static void main(String[] args) {
printSpaceship(
new SpaceshipBuilder()
.name("USS Enterprise")
.captain("Kirk")
.torpedoes(10_000)
.length(288_646)
.build());
}
}