JS Built-ins
DesignPatternsbeginner

Factory β€” Creating different types

πŸ“– Usage Example
function createShape(type) {
  if (type === 'circle') return { type, area: r => Math.PI * r * r };
  if (type === 'square') return { type, area: s => s * s };
}
const c = createShape('circle');

A factory can return different object types based on a parameter.

Factory Pattern β€” Creating Different Types

A factory can create different types of objects based on input parameters.

Challenge: Implement a createVehicle(type) factory that returns:

  • { type: 'car', wheels: 4 } when type is 'car'
  • { type: 'bike', wheels: 2 } when type is 'bike'
  • { type: 'truck', wheels: 6 } when type is 'truck'

Example:

const car = createVehicle('car')
car.wheels // 4
const bike = createVehicle('bike')
bike.wheels // 2
πŸ’‘ Hints (3)
  • β€’ Use if statements or switch to differentiate types
  • β€’ Return appropriate object for each type
  • β€’ Include both type and wheels properties