-
Notifications
You must be signed in to change notification settings - Fork 2
/
CodeBuilder.java
53 lines (44 loc) · 1.24 KB
/
CodeBuilder.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
package creational.builder;
// Exercise: You are asked to implement the Builder design pattern for rendering simple chunks of code.
import java.util.ArrayList;
import java.util.List;
class Field
{
public String name, type;
public Field(String name, String type) {
this.name = name;
this.type = type;
}
}
class CodeBuilder
{
public String className, name, type;
private List<Field> fields = new ArrayList<>();
public CodeBuilder(String className)
{
this.className = className;
}
public CodeBuilder addField(String name, String type)
{
fields.add(new Field(name, type));
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("public class %s\n", this.className));
sb.append("{\n");
for (Field f : fields)
sb.append(String.format(" public %s %s;\n",f.type, f.name));
sb.append("}");
return sb.toString();
}
}
class CodeBuilderDemo {
public static void main(String[] args) {
CodeBuilder cb = new CodeBuilder("Person")
.addField("name", "String")
.addField("age", "int");
System.out.println(cb);
}
}