JS Built-ins
DesignPatternsadvanced

Factory β€” Registry pattern

πŸ“– Usage Example
const registry = {};
function register(type, factory) { registry[type] = factory; }
function create(type, ...args) { return registry[type]?.(...args); }
register('dog', name => ({ name, speak: () => 'woof' }));

A factory registry maps type names to factory functions for dynamic object creation.

Factory Pattern β€” Registry/Type Map

A factory can use a registry (map of type names to constructors) to manage object creation.

Challenge: Implement createShape(type) factory with a registry that creates:

  • { type: 'circle', area: (r) => Math.PI * r * r } for 'circle'
  • { type: 'square', area: (s) => s * s } for 'square'

Use a registry object to store the templates.

Example:

const circle = createShape('circle')
circle.area(2) // ~12.566...
const square = createShape('square')
square.area(4) // 16
πŸ’‘ Hints (3)
  • β€’ Use an object as registry to map type names to shapes
  • β€’ Store both type and area function in registry
  • β€’ Return the appropriate shape object from registry