CreationalTypeScriptverifiedVerified

Abstract Factory Pattern in TypeScript

Provides an interface for creating families of related objects without specifying their concrete classes.

How to Implement the Abstract Factory Pattern in TypeScript

1Step 1: Define the product interfaces

interface Button {
  render(): string;
}

interface TextInput {
  render(): string;
}

2Step 2: Define the abstract factory interface

interface UIFactory {
  createButton(): Button;
  createTextInput(): TextInput;
}

3Step 3: Implement concrete product families

class DarkButton implements Button {
  render() { return "<button class='dark-btn'>Click</button>"; }
}

class DarkTextInput implements TextInput {
  render() { return "<input class='dark-input' />"; }
}

class DarkThemeFactory implements UIFactory {
  createButton() { return new DarkButton(); }
  createTextInput() { return new DarkTextInput(); }
}

// Light Theme Family
class LightButton implements Button {
  render() { return "<button class='light-btn'>Click</button>"; }
}

class LightTextInput implements TextInput {
  render() { return "<input class='light-input' />"; }
}

class LightThemeFactory implements UIFactory {
  createButton() { return new LightButton(); }
  createTextInput() { return new LightTextInput(); }
}

4Step 4: Build forms using any factory

function buildForm(factory: UIFactory): string {
  const button = factory.createButton();
  const input = factory.createTextInput();
  return `Form: ${input.render()} ${button.render()}`;
}

console.log(buildForm(new DarkThemeFactory()));
console.log(buildForm(new LightThemeFactory()));

Abstract Factory Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Abstract Factory Pattern in the Real World

Imagine furnishing a room from IKEA versus a luxury boutique. Each store (factory) produces a complete set of furniture — chairs, tables, sofas — that share a consistent style. You pick the store, and every piece you get matches. You never mix a rustic IKEA chair with a baroque boutique table.