- タイトルまんま
欲しい状態のArticleをメソッドチェーンで作成できるのでとても便利ですね!
builderクラスではconstructorで初期化
各メソッドではプロパティを設定し、自分自身(this)をreturnする
最後にbuildメソッドで欲しいクラス(ここでいうArticle)に自分自身を突っ込むで初期化するって流れですね!
//Article
class Article {
constructor(builder) {
this.title = builder.title;
this.category = builder.category;
this.isPublic = builder.isPublic
this.isFree = builder.isFree;
this.price = builder.price || 0;
}
render(){
console.log(this)
}
}
// builder
class ArticleBuilder {
constructor(title, category){
this.title = title;
this.category = category
this.isPublic = false
this.isFree = true
}
makePublic(){
this.isPublic = true;
return this;
}
makePaid(price){
this.isFree = false;
this.price = price;
return this;
}
build(){
return new Article(this)
}
}
const firstArticle = new ArticleBuilder('First Article', 'News').makePaid(100).makePublic().build();
const secondArticle = new ArticleBuilder('Second Article', 'Music').build()
firstArticle.render()
secondArticle.render()
jsfiddleに書いておきました
consoleで結果が見れるはずです
Edit fiddle - JSFiddle - Code Playground
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
Bitly
Bitly
コメント