Created
December 19, 2021 08:15
-
-
Save msankhala/213ff8cc9a76b16807983d602c17c2da to your computer and use it in GitHub Desktop.
Builder design pattern javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Car { | |
constructor(make, model, year, isForSale = true, isInStock = false) { | |
this.make = make; | |
this.model = model; | |
this.year = year; | |
this.isForSale = isForSale; | |
this.isInStock = isInStock; | |
} | |
toString() { | |
return console.log(JSON.stringify(this)); | |
} | |
} | |
class CarBuilder { | |
constructor(make, model, year) { | |
this.make = make; | |
this.model = model; | |
this.year = year; | |
} | |
notForSale() { | |
this.isForSale = false; | |
return this; | |
} | |
addInStock() { | |
this.isInStock = true; | |
return this; | |
} | |
build() { | |
return new Car(this.make, this.model, this.year, this.isForSale, this.isInStock); | |
} | |
} | |
module.exports = CarBuilder; | |
const CarBuilder = require('./CarBuilder'); | |
const bmw = new CarBuilder('bmw', 'x6', 2020).addInStock().build(); | |
const audi = new CarBuilder('audi', 'a8', 2021).notForSale().build(); | |
const mercedes = new CarBuilder('mercedes-benz', 'c-class', 2019).build(); | |
const bmw = new CarBuilder('bmw', 'x6', 2020, true, true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment