class HtmlElement {
...
static unique_ptr<HtmlBuilder> build(const string& root_name){
return make_unique<HtmlBuilder>(root_name);
}
protected:
HtmlElement(){} //Hide Initializer
};
위 코드의 특징
1. 모든 생성자를 protected로 숨겨 사용자가 사용할 수 없게 함
2. HtmlElement 자체에 팩토리 메서드를 두어 빌더를 생성
3. static으로 선언한 빌더의 unique pointer로 인해 팩토리 메서드 중복 생성 방지
사용 예시:
auto builder = HtmlElement::bulder("ul"); //expected unique_ptr<HtmlBuilder>
builder.add_child("li", "hello").add_child("li", "world"); //흐름식 빌더
빌더로 HtmlElement를 만드는 것이 목적이기 때문에 아래 Operator를 선언
class HtmlBuilder{
operator HtmlElement() const {return root;}
HtmlElement HtmlBuilder::build() const {return root;}
HtmlElement root;
...
};
...
HtmlElement e = HtmlElement::build("ul")
.add_child("li", "hello")
.add_child("li", "world");