https://zetcode.com/javascript/builderpattern/
https://javascript.plainenglish.io/javascript-design-patterns-builder-pattern-608dbb2020a
class BookBuilder {
constructor() {
this.name = '';
this.author = '';
this.price = 0;
this.category = '';
}
withName(name) {
this.name = name;
return this;
}
withAuthor(author) {
this.author = author;
return this;
}
withPrice(price) {
this.price = price;
return this;
}
withCategory(category) {
this.category = category;
return this;
}
build() {
return {
name: this.name,
author: this.author,
prices: this.price,
category: this.category
}
}
}
//Calling the builder class
const book = new BookBuilder()
.withName("The Reckonings")
.withAuthor('Lacy Johnson')
.withPrice(31)
.withCategory('Literature')
.build();
Class
class CampgroundBuilder {
constructor() {
this.title;
this.price;
this.description;
this.location;
this.geometry;
this.images;
this.author;
}
withTitle(title) {
this.title = title;
return this;
}
withPrice(price) {
this.price = price;
return this;
}
withDescription(description) {
this.description = description;
return this;
}
withLocation(location) {
this.location = location;
return this;
}
withGeometry(geometry) {
this.geometry = geometry;
return this;
}
withImages(images) {
this.images = images;
return this;
}
withAuthor(author) {
this.author = author;
return this;
}
build() {
return {
title: this.title,
price: this.price,
description: this.description,
location: this.location,
geometry: this.geometry,
images: this.images,
author: this.author,
};
}
}
module.exports = CampgroundBuilder;
Create objects:
const newCampground = new CampgroundBuilder()
.withTitle(title)
.withPrice(price)
.withDescription(description)
.withLocation(location)
.withGeometry(geometry)
.withImages(images)
.withAuthor(author)
.build();