Creational Patterns — Series 2

Preview — 3 of 10 questions

What is logged, and what pattern does this code demonstrate?

javascript
class PizzaBuilder {
  constructor() {
    this.toppings = [];
  }
  addTopping(topping) {
    this.toppings.push(topping);
    return this;
  }
  build() {
    return `Pizza with: ${this.toppings.join(', ')}`;
  }
}

const pizza = new PizzaBuilder().addTopping('cheese').addTopping('pepperoni').build();

console.log(pizza);
A"Pizza with: cheese, pepperoni" — the Proxy pattern, controlling access to the pizza object.
B"Pizza with: cheese, pepperoni" — the Builder pattern: it constructs a complex object step by step through a fluent, chainable API, rather than requiring every option to be supplied at once in a single constructor call.
C"Pizza with: cheese, pepperoni" — the Singleton pattern, ensuring only one PizzaBuilder can ever exist.
D"Pizza with: cheese, pepperoni" — the Observer pattern, notifying the pizza of each new topping.

What is logged?

javascript
const carPrototype = {
  wheels: 4,
  describe() {
    return `A car with ${this.wheels} wheels`;
  },
};

const myCar = Object.create(carPrototype);
myCar.color = 'red';

console.log(myCar.describe());
console.log(myCar.wheels);
console.log(Object.getPrototypeOf(myCar) === carPrototype);
A"A car with undefined wheels", undefined, false
BTypeError: myCar.describe is not a function
C"A car with 4 wheels", 4, true
D"A car with 4 wheels", 4, false

What is logged?

javascript
class LightButton {
  render() {
    return 'Light button';
  }
}
class LightCheckbox {
  render() {
    return 'Light checkbox';
  }
}
class DarkButton {
  render() {
    return 'Dark button';
  }
}
class DarkCheckbox {
  render() {
    return 'Dark checkbox';
  }
}

class LightThemeFactory {
  createButton() {
    return new LightButton();
  }
  createCheckbox() {
    return new LightCheckbox();
  }
}
class DarkThemeFactory {
  createButton() {
    return new DarkButton();
  }
  createCheckbox() {
    return new DarkCheckbox();
  }
}

function renderUI(factory) {
  return [factory.createButton().render(), factory.createCheckbox().render()];
}

console.log(renderUI(new DarkThemeFactory()));
A["Light button", "Light checkbox"]
BTypeError: factory.createButton is not a function
C["Dark button", "Light checkbox"]
D["Dark button", "Dark checkbox"]

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.