Skip to content
Velloreth
Programming 6 min read

The Factory Pattern Explained With Real Examples

Factories create objects without exposing which class is instantiated. Learn simple factories, factory methods, and when they earn their keep.

By

What a factory does

A factory is responsible for creating objects. Instead of calling new directly, callers ask the factory for what they need, and the factory decides which class to instantiate.

// Without a factory: the caller knows every class
let parser;
if (format === 'json') parser = new JsonParser();
else if (format === 'yaml') parser = new YamlParser();
else if (format === 'toml') parser = new TomlParser();
else throw new Error('Unknown format');

// With a factory: the caller knows one function
const parser = createParser(format);

The benefit is that the knowledge of which classes exist lives in one place. Adding a format means editing the factory, not every call site.

The simple factory

The simplest form is a function with a switch.

interface Parser {
  parse(text: string): Record<string, unknown>;
}

class JsonParser implements Parser {
  parse(text: string) { return JSON.parse(text); }
}

class YamlParser implements Parser {
  parse(text: string) { return yaml.load(text) as Record<string, unknown>; }
}

function createParser(format: string): Parser {
  switch (format) {
    case 'json': return new JsonParser();
    case 'yaml': return new YamlParser();
    default: throw new Error(`Unsupported format: ${format}`);
  }
}

This is not one of the Gang of Four patterns — it is a convention — but it is the form you will use most often. It is simple, testable, and solves the real problem.

When it earns its keep: when the choice depends on runtime data, when creation involves setup, or when the set of implementations is likely to grow.

The factory method

The factory method defers creation to subclasses. The base class defines the algorithm; the subclass decides which product to create.

abstract class ReportGenerator {
  // the template method
  generate(data: ReportData): string {
    const formatter = this.createFormatter(); // factory method
    return formatter.format(data);
  }

  protected abstract createFormatter(): Formatter;
}

class PdfReportGenerator extends ReportGenerator {
  protected createFormatter(): Formatter {
    return new PdfFormatter();
  }
}

class HtmlReportGenerator extends ReportGenerator {
  protected createFormatter(): Formatter {
    return new HtmlFormatter();
  }
}

ReportGenerator knows how to generate a report but not how to format it. Each subclass supplies the formatter. The base class is closed for modification and open for extension.

When it earns its keep: when a family of classes shares an algorithm but varies in one creation step, and when the variation is a compile-time decision.

The abstract factory

The abstract factory creates families of related objects that must be used together.

interface Button { render(): string; }
interface Checkbox { render(): string; }

interface UIFactory {
  createButton(): Button;
  createCheckbox(): Checkbox;
}

class WindowsFactory implements UIFactory {
  createButton(): Button { return new WindowsButton(); }
  createCheckbox(): Checkbox { return new WindowsCheckbox(); }
}

class MacFactory implements UIFactory {
  createButton(): Button { return new MacButton(); }
  createCheckbox(): Checkbox { return new MacCheckbox(); }
}

The point is consistency. A MacFactory never produces a Windows button, so the UI cannot end up with mismatched widgets. The client code takes a UIFactory and never knows which platform it is on.

When it earns its keep: when you have several families of related objects and mixing them would be a bug. This is rarer than the other two forms.

Where factories appear in real code

Parsing by format. Choosing a parser from a file extension or content type.

Database drivers. Selecting a driver from a connection string.

Payment providers. Creating a gateway from a configured provider name.

Notification channels. Building an email, SMS, or push sender from a user preference.

UI components. Rendering a platform-appropriate widget.

Serialisation. Choosing a serialiser from a schema or a type tag.

Test fixtures. Building objects with sensible defaults and overrides.

The common thread is a runtime decision about which implementation to use.

Factories and dependency injection

Dependency injection containers handle construction and wiring. This overlaps with factories, and it is worth understanding the division.

The container handles static wiring. Which database, which logger, which configuration — decided at startup, fixed for the process lifetime.

Factories handle runtime choices. Which parser for this file, which gateway for this user’s region, which strategy for this order — decided per call.

class ImportService {
  constructor(
    private logger: Logger,          // injected, fixed
    private parserFactory: ParserFactory, // injected, used per call
  ) {}

  async import(path: string) {
    const format = extname(path).slice(1);
    const parser = this.parserFactory.create(format); // runtime choice
    this.logger.info(`Parsing ${path} as ${format}`);
    return parser.parse(await readFile(path, 'utf8'));
  }
}

The factory itself is injected, so it can be faked in tests. The choice it makes is a runtime decision the container cannot make.

When a factory is not worth it

One implementation, no variation.

// Pointless
class UserServiceFactory {
  create(): UserService { return new UserService(); }
}

This adds a type and a layer to do what new UserService() does.

Creation is trivial. If new SomeClass() is all that is needed, a factory is ceremony.

The switch is in one place anyway. If only one call site chooses the implementation, moving the switch into a factory just relocates it.

You are hiding a dependency. A factory that always returns the same concrete type is often a way to avoid injecting that type properly.

The test: does the factory encapsulate a decision, a configuration, or a setup step? If not, it is indirection.

A practical example: test fixtures

One place factories are unambiguously useful is building test data.

function makeUser(overrides: Partial<User> = {}): User {
  return {
    id: 'test-id',
    email: 'test@example.com',
    name: 'Test User',
    createdAt: new Date('2026-01-01'),
    ...overrides,
  };
}

const admin = makeUser({ email: 'admin@example.com', role: 'admin' });

Every test gets a valid object with only the relevant fields overridden. Adding a required field means editing one function, not every test. This is the factory pattern applied to test data, and it is one of the highest-value uses.

Common mistakes

A factory that returns any or Object. The caller loses type information, which defeats the purpose in a typed language.

A factory with a growing switch that never gets refactored. If the switch has twenty cases, consider a registry map instead.

A factory that does too much. If it creates objects, configures them, connects them, and starts them, it is doing several jobs.

Throwing on unknown input without a clear message. The factory is the right place to give a helpful error listing the supported options.

Using a factory to avoid a circular dependency. This usually indicates a design problem rather than a creation problem.

Practical guidance

  • Use a simple factory function for runtime choices among implementations.
  • Use the factory method when subclasses should control creation.
  • Use an abstract factory only for families of related objects.
  • Inject the factory so it can be faked in tests.
  • Return a typed interface, never any.
  • Skip the factory when creation is a plain constructor call.
  • Use factories for test fixtures — it is one of their best applications.

For the related patterns, see design patterns for beginners and dependency injection without a framework. For the design principles, SOLID principles explained and interfaces vs abstract classes.

Quotable summary

A factory centralises object creation so callers ask for what they need without knowing which class provides it. The simple factory is a function with a switch, the factory method defers creation to subclasses, and the abstract factory creates families of related objects that must be used together. Factories earn their keep when creation involves a runtime decision, configuration, or setup that callers should not repeat, and they are especially valuable for test fixtures. A factory for a single implementation with no variation is indirection without benefit. Dependency injection containers handle static wiring at startup, while factories handle runtime choices that depend on data the container cannot know in advance.

Frequently asked questions

What is the factory pattern in simple terms?
A factory is a function or class whose job is to create other objects. Instead of calling new directly, you ask the factory for what you need, and it decides which class to instantiate.
What is the difference between a simple factory and a factory method?
A simple factory is one function that returns different types based on its arguments. A factory method is a method that subclasses override to control which type is created, deferring the decision to the subclass.
What is an abstract factory?
An abstract factory creates families of related objects. For example, a UI toolkit factory might create a button, a checkbox, and a dialog that all match the same platform style, so you never mix Windows and macOS widgets.
When should I use a factory?
Use one when object creation involves a decision, configuration, or setup that callers should not repeat. If creation is just new SomeClass(), a factory adds indirection without benefit.
Is a factory the same as a constructor?
No. A constructor creates one specific class. A factory can choose among several classes, return a cached instance, or perform setup before returning. It is a higher-level abstraction over construction.
Do I need a factory with dependency injection?
Often not for wiring, because the container handles construction. Factories remain useful when the choice depends on runtime data, such as a user's plan or a file's format, which the container cannot know in advance.