Skip to content

Instantly share code, notes, and snippets.

@jiraguha
Created May 7, 2020 15:47
Show Gist options
  • Save jiraguha/3fd01ab620d2280880bee93a42bae314 to your computer and use it in GitHub Desktop.
Save jiraguha/3fd01ab620d2280880bee93a42bae314 to your computer and use it in GitHub Desktop.
Builder in js
class Rectangle {
constructor(hauteur, largeur, color) {
this.hauteur = hauteur;
this.largeur = largeur;
this.color = color;
}
}
class RectangleBuilder {
withHauteur(hauteur) {
this.hauteur = hauteur;
return this
}
withLargeur(largeur) {
this.hauteur = largeur;
return this
}
withColor() {
return new ColorBuilder(this)
}
build() {
return new Rectangle(this.hauteur, this.hauteur, this.color)
}
}
class ColorBuilder {
constructor(recBulder) {
this.recBulder = recBulder
}
withBlue(b) {
this.b = b;
return this
}
withGreen(g) {
this.g = g;
return this
}
withRed(r) {
this.r = r;
return this
}
build() {
this.recBulder.color = new Color(this.r, this.b, this.g)
return this.recBulder
}
}
class Color {
constructor(r, b, g) {
this.r = r;
this.b = b;
this.g = g;
}
}
console.log(
JSON.stringify(
new RectangleBuilder()
.withHauteur(100)
.withColor()
.withBlue(29)
.withGreen(40)
.withRed(100)
.build()
.withLargeur(53)
.build()
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment