Meal Builder

Christopher T.

2020-10-06

Share This Post

Create a meal builder API using the Builder Pattern.

This code features a MealDirector that wraps the core api MealBuilder.

class MealBuilder {
  init() {
    this.meal = new Meal()
  }

  addMain(type) {
    this.meal.main = new MainItem(type)
  }

  addSide(type) {
    this.meal.side = new SideItem(type)
  }

  addDrink(type) {
    this.meal.drink = new DrinkItem(type)
  }

  addToy(type) {
    this.meal.toy = new ToyItem(type)
  }

  get() {
    return this.meal
  }
}

class MealDirector {
  create(main, side, drink, toy) {
    const builder = new MealBuilder()
    builder.init()
    builder.addMain(main)
    builder.addSide(side)
    builder.addDrink(drink)
    builder.addToy(toy)
    return builder.get()
  }
}

const mealDirector = new MealDirector()

mealDirector.create('hamburger', 'fries', 'coke', 'car')

One strategy commonly used in conjunction is to integrate the fluent api so that these methods can be chained. To do that, we can write return this at the end of each method in the core api:

class MealBuilder {
  init() {
    this.meal = new Meal()
    return this
  }

  addMain(type) {
    this.meal.main = new MainItem(type)
    return this
  }

  addSide(type) {
    this.meal.side = new SideItem(type)
    return this
  }

  addDrink(type) {
    this.meal.drink = new DrinkItem(type)
    return this
  }

  addToy(type) {
    this.meal.toy = new ToyItem(type)
    return this
  }

  get() {
    return this.meal
  }
}

In this way the consumer using the api can write code more "fluently" as so:

class MealDirector {
  create(main, side, drink, toy) {
    const builder = new MealBuilder()
    builder.init().addMain(main).addSide(side).addDrink(drink).addToy(toy)
    return builder.get()
  }
}

const mealDirector = new MealDirector()


Tags


Subscribe to the Newsletter
Get continuous updates
© jsmanifest 2020