Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
JS

JavaScript

The language of the web, on the client, the server and the edge.

Paradigm
Multi-paradigm, prototype-based, functional
Typing
Dynamic, weak (TypeScript adds static types)
Memory
Garbage collected
Runs
V8 / SpiderMonkey / JSC engines (JIT)
Concurrency
Single-threaded event loop, workers
Creational pattern

Abstract Factory

Intent

Produces families of related objects without specifying their concrete classes.

Problem

A UI kit needs buttons, checkboxes and menus that match: all Mac or all Windows, never mixed.

Solution

Declare an interface with one creation method per product; each concrete factory produces one consistent family.

Real-world analogy

Think of it like this

A furniture shop sells matching sets: a Victorian chair, sofa and table, or a Modern set. You never get a Victorian chair with a Modern sofa.

Structure

association / extends implements / depends on
«interface» AbstractFactory + createProductA(): ProductA+ createProductB(): ProductB 3 ConcreteFactory1 + createProductA(): ProductA+ createProductB(): ProductB 4 Client - factory: AbstractFactory 5 «interface» ProductA 1 ConcreteProductA1 2

Hover or tap a numbered role to highlight it in the diagram.

  1. 1ProductA — Abstract Products declare an interface for each distinct product of the family.
  2. 2ConcreteProductA1 — Concrete Products are variants grouped by family (A1 goes with B1).
  3. 3AbstractFactory — Abstract Factory declares one creation method per abstract product.
  4. 4ConcreteFactory1 — Concrete Factories each produce exactly one family of products.
  5. 5Client — Client only uses the abstract interfaces, so any factory or family can be plugged in.

Code example

A JavaScript code sample for Abstract Factory is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Abstract Factory when code must work with families of related products.

Use Abstract Factory when you want to enforce that products from one family are used together.

Pros and cons

Pros

  • Products from a factory are guaranteed compatible
  • Isolates concrete classes from client code

Cons

  • Adding a new product kind changes every factory

Relations with other patterns

Check yourself

Check yourself

A game must create enemies, weapons and terrain that all match the selected world: ice, desert or jungle.

Saved in this browser only. Part of Creational patterns (0/5).