-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBuilder.java
More file actions
48 lines (38 loc) · 1.24 KB
/
Builder.java
File metadata and controls
48 lines (38 loc) · 1.24 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
import java.util.List;
import java.util.ArrayList;
// A builder is a separate component for building (constructing) complex objects
// Builders often employ the fluent style
class CodeBuilder {
private final String className;
private final List<CodeField> fields = new ArrayList<>();
CodeBuilder(String className) {
this.className = className;
}
CodeBuilder addField(String name, String type) {
fields.add(new CodeField(name, type));
return this;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("public class %s%n{%n", className));
fields.stream().forEach(sb::append);
sb.append("}");
return sb.toString();
}
}
class CodeField {
private final String name, type;
CodeField(String name, String type) {
this.name = name;
this.type = type;
}
public String toString() {
return String.format(" public %s %s;%n", type, name);
}
}
class DemoBuilder {
public static void main(String args[]) {
CodeBuilder cb = new CodeBuilder("Person").addField("name", "String").addField("age", "int");
System.out.println(cb);
}
}