Course contentsShow
← JavaScript
Lesson 1819 of 2,72338. Object-Oriented PatternsFree lesson

Factory Functions for Composition

Use factory functions to return objects that compose multiple concerns without relying on class hierarchies.

Factory Functions for Composition

You'll learn how to use factory functions to build flexible, composable objects without the pitfalls of class inheritance.

The Core Idea

Instead of building complex class hierarchies where a FlyingDog inherits from both Dog and Flyer (which JavaScript can't even do directly), you create factory functions that return objects composed of just the behaviors you need. Each factory assembles different pieces of functionality like building blocks.

Think of it like ordering a custom pizza: rather than choosing from preset combinations (inheritance), you pick exactly which toppings (behaviors) you want for each pizza (object).

How It Works

A factory function for composition typically:

  1. Accepts configuration or dependencies
  2. Assembles multiple behavior objects together
  3. Returns a single composed object with all desired capabilities
// Behavior factories
const canSwim = (name) => ({
  swim: () => `${name} is swimming`
});

const canFly = (name) => ({
  fly: () => `${name} is flying`
});

// Composing factory
function createDuck(name) {
  return {
    name,
    ...canSwim(name),
    ...canFly(name)
  };
}

const duck = createDuck('Donald');
duck.swim(); // "Donald is swimming"
duck.fly();  // "Donald is flying"

Each small factory provides one concern. The main factory composes them together using spread syntax, avoiding inheritance entirely.

Why This Matters

You get exactly the behaviors you need without forcing objects into rigid inheritance trees. Need a flying fish? Compose canSwim and canFly. Need a walking fish? Compose canSwim and canWalk. No awkward parent classes required.

Key Takeaway: Factory functions let you compose objects from small, reusable behavior units, giving you inheritance-free flexibility to mix and match capabilities as needed.