빌더 패턴은 무엇일까? 무엇을 조심해야 할까? 어떤식으로 활용하는 것이 좋을까?
StringBuilder builder = new StringBuilder(4096);
builder.append(heading);
builder.append(newLine);
builder.append(newLine);
builder.append(leadingParagraph);
builder.append(newLine);
for (KeyValue kv: data) {
builder.append(" * ");
builder.append(kv.getKey());
builder.append(": ");
builder.append(kv.getValue());
builder.append(newLine);
}
String document = builder.toString();
StringBuilder
를 사용하면 편하다.toString()
을 통해 결과물을 가져옴StringBuilder builder = new StringBuilder(1024 * 1024);
builder.append(heading)
.append(newLine)
.append(newLine);
builder.append(leadingParagraph)
.append(newLine);
for (KeyValue kv: data) {
builder.append(" * ");
.append(kv.getKey());
.append(": ");
.append(kv.getValue());
.append(newLine);
}
String document = builder.toString();
return this
를 하지?public final class Employee {
private String firstName;
private String lastName;
private int id;
private int yearStarted;
private int age;
public Employee(String firstName, String lastName, int id, int, yearStarted, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.yearStarted = yearStarted;
this.age = age;
}
}
Employee wansik = new Employee("Wansik", "Choi", 1, 1995, 28);
Employee howon = new Employee("Kim", "Howon", 30, 1993, 2);
Employee howon = new EmployeeBuilder(1)
.withAge(30)
.withStartingYear(1993)
.withName("Howon", "Kim")
.build();
Employee howon = new EmployeeBuilder(1)
.withAge(30)
.withName("Howon", "Kim")
.build();
StringBuilder
는 유효한 개체만 반환했다.String
만 다뤘기 때문에, 언제 호출해도 유효한 String
개체가 나온다.public final class Employee {
private String firstName;
private String lastName;
private int id;
private int yearStarted;
private int age;
public Employee(CreateEmployeeParams params) {
this.firstName = params.first;
this.lastName = params.lastName;
this.id = params.id;
this.yearStarted = params.yearStarted;
this.age = params.age;
}
}
CreateEmployeeParams params = new CreateEmployeeParams();
params.firstName = "Howon";
params.lastName = "Kim";
params.id = 1;
params.age = 30;
params.yearStarted = 1993;
Employee howon = new Employee(params)
with~
, build()
호출하고 하는 방식을 쓸 이유가 없다는 말을 하고 싶은 것Employee(firstName: "Howon", lastName: "Kim", id: 1, yearStarted: 1993, age: 30);
UIView
에 다양한 요소를 넣을 수 있지만, 넣지 않아도 UIView
자체가 의미있는 경우가 있겠다..csv
파일이 있다고 생각해보자.CsvReader reader = new CsvReader(csvText);
HtmlTableBuilder builder = new HtmlTableBuilder();
reader.writeTo(builder);
HtmlDocument html = builder.toHtmlDocument();
CsvReader reader = new CsvReader(csvText);
MarkdownTableBuilder = builder = new MarkdownTableBuilder();
reader.writeTo(builder);
String mdText = builder.toMarkDownText();