On this page

Factory Method

Factory Method is the creational pattern you have probably used without naming it. Every time a collection hands you an Iterator without telling you its class, every time a framework calls a method you overrode to get "your" kind of object, a factory method is at work. The pattern answers a narrow question: how can a class that does most of a job leave the choice of one collaborator's concrete type to someone else?

The name causes confusion because "factory" is used loosely. People say "factory method" for three different things: the GoF pattern (an overridable creation method inside a class that also does other work), a simple factory (a function with a switch that returns one of several classes), and static factory methods such as List.of(...). This page covers the GoF pattern properly and then places the other two next to it, so you can tell them apart in an interview. The grouped creational patterns page has the short version.

CategoryCreational (class-based in its original form)
Also known asVirtual Constructor
SolvesA general algorithm needs an object whose concrete type varies
Main costOne subclass (or function) per product variant, plus an extra level of indirection
Modern formPass a factory function or register constructors in a map

Intent

Define a method for creating an object, and let subclasses (or a supplied function) decide which concrete class to create. The rest of the class works only with the product's interface, so it never names a concrete product type.

Put differently: the creator owns the workflow, the subclass owns the choice. That split is the whole pattern.

The problem

Imagine a small data-import service. It reads a text file, parses each line into a record, rejects invalid rows, removes duplicates and reports counts. The steps around parsing are the same for every format. Only the parser changes. The first version supports CSV and JSON Lines, and the format check sits inside the import loop.

import java.util.*;

record Customer(String email, String name) {}

class ImportService {
    // Every new format means editing this method, retesting CSV and JSON,
    // and redeploying the class that holds the shared validation rules.
    Map<String, Integer> importFile(String format, String text) {
        Set<String> seen = new HashSet<>();
        int imported = 0, rejected = 0;
        for (String line : text.strip().split("\n")) {
            Customer c;
            if (format.equals("csv")) {
                String[] parts = line.split(",");
                c = new Customer(parts[0].trim(), parts[1].trim());
            } else if (format.equals("jsonl")) {
                String email = line.replaceAll(".*\"email\"\\s*:\\s*\"([^\"]*)\".*", "$1");
                String name = line.replaceAll(".*\"name\"\\s*:\\s*\"([^\"]*)\".*", "$1");
                c = new Customer(email, name);
            } else {
                throw new IllegalArgumentException("unknown format " + format);
            }
            if (!c.email().contains("@") || !seen.add(c.email())) { rejected++; continue; }
            imported++;
        }
        return Map.of("imported", imported, "rejected", rejected);
    }
}

public class Before {
    public static void main(String[] args) {
        Map<String, Integer> r = new ImportService().importFile("csv", "a@x.io, Ann\nbad, Bob\na@x.io, Ann");
        if (r.get("imported") != 1 || r.get("rejected") != 2) throw new AssertionError(r);
        System.out.println(r);
    }
}
import assert from "node:assert/strict";

type Customer = { email: string; name: string };

class ImportService {
  importFile(format: string, text: string): { imported: number; rejected: number } {
    const seen = new Set<string>();
    let imported = 0, rejected = 0;
    for (const line of text.trim().split("\n")) {
      let c: Customer;
      if (format === "csv") {
        const [email, name] = line.split(",").map((s) => s.trim());
        c = { email, name };
      } else if (format === "jsonl") {
        c = JSON.parse(line) as Customer;
      } else {
        throw new Error(`unknown format ${format}`);
      }
      if (!c.email.includes("@") || seen.has(c.email)) { rejected++; continue; }
      seen.add(c.email);
      imported++;
    }
    return { imported, rejected };
  }
}

const r = new ImportService().importFile("jsonl", '{"email":"a@x.io","name":"Ann"}\n{"email":"nope","name":"B"}');
assert.deepEqual(r, { imported: 1, rejected: 1 });
console.log(r);

What's wrong with it:

  • Two reasons to change in one method. The import workflow (validate, dedupe, count) and the per-format parsing live together. A change to CSV quoting rules risks breaking deduplication, and the reverse.
  • It's closed to extension. Adding XML or fixed-width files means editing importFile. That violates the open/closed principle: the stable part of the code has to be reopened for every new variant.
  • Testing is awkward. You can't test the workflow with a trivial fake parser. Every workflow test also exercises real parsing.
  • The if chain spreads. Soon a previewFile method needs the same branching, then countLines, and the format switch is duplicated across the class.

The pattern's fix: keep the workflow in one place, and move "which parser?" into a single overridable method.

Structure

classDiagram
    class Importer {
        <<abstract>>
        +importFile(text) ImportResult
        #createParser()* RecordParser
    }
    class CsvImporter {
        #createParser() RecordParser
    }
    class JsonLinesImporter {
        #createParser() RecordParser
    }
    class RecordParser {
        <<interface>>
        +parse(line) Customer
    }
    class CsvParser {
        +parse(line) Customer
    }
    class JsonLinesParser {
        +parse(line) Customer
    }
    Importer <|-- CsvImporter
    Importer <|-- JsonLinesImporter
    RecordParser <|.. CsvParser
    RecordParser <|.. JsonLinesParser
    Importer ..> RecordParser : uses
    CsvImporter ..> CsvParser : creates
    JsonLinesImporter ..> JsonLinesParser : creates

There are two parallel hierarchies: creators on the left and products on the right. importFile (the workflow) is written once in the abstract creator and calls createParser(). Each concrete creator overrides only that method. The * marks an abstract method.

Participants

  • Product (RecordParser). The interface for the objects the factory method creates. The creator's workflow depends only on this.
  • Concrete products (CsvParser, JsonLinesParser). The real implementations.
  • Creator (Importer). Declares the factory method, which returns a Product. It may provide a default implementation. Crucially, the creator also uses the product as part of a larger operation. A class whose only job is creation is a factory, but not the Factory Method pattern.
  • Concrete creators (CsvImporter, JsonLinesImporter). Override the factory method to return a specific concrete product.

Clients usually pick a concrete creator once (often at the composition root) and then call the creator's ordinary operations without thinking about products.

Implementation

The three versions below are the same design. The workflow is written once, and each subclass contributes one method. The JSON Lines parser is intentionally minimal in Java to avoid a library dependency. In real code you'd use Jackson or Gson.

import java.util.*;

record Customer(String email, String name) {}

record ImportResult(List<Customer> imported, int rejected) {}

interface RecordParser {
    Customer parse(String line);
}

final class CsvParser implements RecordParser {
    public Customer parse(String line) {
        String[] parts = line.split(",", -1);
        if (parts.length != 2) throw new IllegalArgumentException("expected 2 columns: " + line);
        return new Customer(parts[0].trim(), parts[1].trim());
    }
}

final class JsonLinesParser implements RecordParser {
    public Customer parse(String line) {
        return new Customer(field(line, "email"), field(line, "name"));
    }
    // Toy extraction for flat {"key": "value"} objects. Use a JSON library in real code.
    private static String field(String json, String key) {
        java.util.regex.Matcher m = java.util.regex.Pattern
            .compile("\"" + key + "\"\\s*:\\s*\"([^\"]*)\"").matcher(json);
        if (!m.find()) throw new IllegalArgumentException("missing " + key);
        return m.group(1);
    }
}

abstract class Importer {
    // The workflow: written once, shared by every format.
    public final ImportResult importFile(String text) {
        RecordParser parser = createParser();          // the factory method call
        Set<String> seen = new HashSet<>();
        List<Customer> imported = new ArrayList<>();
        int rejected = 0;
        for (String line : text.strip().split("\n")) {
            try {
                Customer c = parser.parse(line);
                if (!c.email().contains("@") || !seen.add(c.email())) { rejected++; continue; }
                imported.add(c);
            } catch (IllegalArgumentException e) {
                rejected++;
            }
        }
        return new ImportResult(List.copyOf(imported), rejected);
    }

    // The factory method: subclasses decide which parser.
    protected abstract RecordParser createParser();
}

final class CsvImporter extends Importer {
    protected RecordParser createParser() { return new CsvParser(); }
}

final class JsonLinesImporter extends Importer {
    protected RecordParser createParser() { return new JsonLinesParser(); }
}

public class Main {
    static void check(boolean condition, Object message) {
        if (!condition) throw new AssertionError(message);
    }

    public static void main(String[] args) {
        ImportResult csv = new CsvImporter().importFile("ann@x.io, Ann\nbroken line\nbob@x.io, Bob\nann@x.io, Ann");
        check(csv.imported().size() == 2 && csv.rejected() == 2, csv);

        ImportResult jsonl = new JsonLinesImporter().importFile(
            "{\"email\": \"cy@x.io\", \"name\": \"Cy\"}\n{\"email\": \"nope\", \"name\": \"Dee\"}");
        check(jsonl.imported().equals(List.of(new Customer("cy@x.io", "Cy"))) && jsonl.rejected() == 1, jsonl);

        // A test can subclass with a fake parser to exercise only the workflow.
        Importer fake = new Importer() {
            protected RecordParser createParser() { return line -> new Customer(line, "x"); }
        };
        check(fake.importFile("a@b\na@b\nc@d").imported().size() == 2, "dedupe works with any parser");
        System.out.println("csv=" + csv.imported().size() + " jsonl=" + jsonl.imported().size());
    }
}
import json
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Protocol


@dataclass(frozen=True)
class Customer:
    email: str
    name: str


@dataclass(frozen=True)
class ImportResult:
    imported: tuple[Customer, ...]
    rejected: int


class RecordParser(Protocol):
    def parse(self, line: str) -> Customer: ...


class CsvParser:
    def parse(self, line: str) -> Customer:
        parts = [p.strip() for p in line.split(",")]
        if len(parts) != 2:
            raise ValueError(f"expected 2 columns: {line!r}")
        return Customer(*parts)


class JsonLinesParser:
    def parse(self, line: str) -> Customer:
        data = json.loads(line)
        return Customer(data["email"], data["name"])


class Importer(ABC):
    def import_file(self, text: str) -> ImportResult:
        parser = self.create_parser()            # the factory method call
        seen: set[str] = set()
        imported: list[Customer] = []
        rejected = 0
        for line in text.strip().splitlines():
            try:
                customer = parser.parse(line)
            except (ValueError, KeyError):       # json.JSONDecodeError is a ValueError
                rejected += 1
                continue
            if "@" not in customer.email or customer.email in seen:
                rejected += 1
                continue
            seen.add(customer.email)
            imported.append(customer)
        return ImportResult(tuple(imported), rejected)

    @abstractmethod
    def create_parser(self) -> RecordParser:
        """Subclasses decide which parser the workflow uses."""


class CsvImporter(Importer):
    def create_parser(self) -> RecordParser:
        return CsvParser()


class JsonLinesImporter(Importer):
    def create_parser(self) -> RecordParser:
        return JsonLinesParser()


csv_result = CsvImporter().import_file("ann@x.io, Ann\nbroken line\nbob@x.io, Bob\nann@x.io, Ann")
assert len(csv_result.imported) == 2 and csv_result.rejected == 2, csv_result

jsonl_result = JsonLinesImporter().import_file('{"email": "cy@x.io", "name": "Cy"}\nnot json')
assert jsonl_result.imported == (Customer("cy@x.io", "Cy"),) and jsonl_result.rejected == 1


class FakeParser:
    def parse(self, line: str) -> Customer:
        return Customer(line, "x")


class FakeImporter(Importer):
    def create_parser(self) -> RecordParser:
        return FakeParser()


assert len(FakeImporter().import_file("a@b\na@b\nc@d").imported) == 2
print("csv", len(csv_result.imported), "jsonl", len(jsonl_result.imported))
import assert from "node:assert/strict";

type Customer = Readonly<{ email: string; name: string }>;
type ImportResult = Readonly<{ imported: readonly Customer[]; rejected: number }>;

interface RecordParser {
  parse(line: string): Customer;
}

class CsvParser implements RecordParser {
  parse(line: string): Customer {
    const parts = line.split(",").map((p) => p.trim());
    if (parts.length !== 2) throw new Error(`expected 2 columns: ${line}`);
    return { email: parts[0], name: parts[1] };
  }
}

class JsonLinesParser implements RecordParser {
  parse(line: string): Customer {
    const data: unknown = JSON.parse(line);
    if (typeof data !== "object" || data === null) throw new Error("not an object");
    const { email, name } = data as Record<string, unknown>;
    if (typeof email !== "string" || typeof name !== "string") throw new Error("bad fields");
    return { email, name };
  }
}

abstract class Importer {
  importFile(text: string): ImportResult {
    const parser = this.createParser();          // the factory method call
    const seen = new Set<string>();
    const imported: Customer[] = [];
    let rejected = 0;
    for (const line of text.trim().split("\n")) {
      let customer: Customer;
      try {
        customer = parser.parse(line);
      } catch {
        rejected++;
        continue;
      }
      if (!customer.email.includes("@") || seen.has(customer.email)) { rejected++; continue; }
      seen.add(customer.email);
      imported.push(customer);
    }
    return { imported, rejected };
  }

  protected abstract createParser(): RecordParser;
}

class CsvImporter extends Importer {
  protected createParser(): RecordParser { return new CsvParser(); }
}

class JsonLinesImporter extends Importer {
  protected createParser(): RecordParser { return new JsonLinesParser(); }
}

const csv = new CsvImporter().importFile("ann@x.io, Ann\nbroken line\nbob@x.io, Bob\nann@x.io, Ann");
assert.equal(csv.imported.length, 2);
assert.equal(csv.rejected, 2);

const jsonl = new JsonLinesImporter().importFile('{"email":"cy@x.io","name":"Cy"}\nnot json');
assert.deepEqual(jsonl.imported, [{ email: "cy@x.io", name: "Cy" }]);
assert.equal(jsonl.rejected, 1);

class FakeImporter extends Importer {
  protected createParser(): RecordParser { return { parse: (line) => ({ email: line, name: "x" }) }; }
}
assert.equal(new FakeImporter().importFile("a@b\na@b\nc@d").imported.length, 2);
console.log(`csv=${csv.imported.length} jsonl=${jsonl.imported.length}`);

Points worth noticing in the implementation:

  • importFile is final in Java. Subclasses customise the product, not the workflow. If they could override importFile too, the guarantee "every format gets the same validation" would be gone. This is the same move Template Method makes, and Factory Method is often described as a template method whose varying step happens to be creation.
  • The factory method is protected. It's an extension point for subclasses, not part of the public API. Clients call importFile.
  • Adding XML is purely additive. Write XmlParser and XmlImporter. No existing class changes, so nothing already working needs retesting.
  • The test seam comes for free. The fake importer in each example tests deduplication with a one-line parser. That's often the most practical benefit in day-to-day work.

Variations you'll meet

The GoF form uses inheritance. Modern code often gets the same benefit with less ceremony. All of the variations below keep the essential idea, the workflow doesn't name concrete products, but they move the choice to a different place.

1. A default product

The creator doesn't have to be abstract. It can return a sensible default that subclasses may override. Frameworks do this constantly: a base controller creates a default view resolver, a base test case creates a default fixture, and you override the method only when you need something else.

2. A parameterised factory method

createParser(String format) takes an argument and returns one of several products. This is convenient, but it brings the switch back inside the creator, so you lose open/closed extension unless subclasses can extend the switch by overriding and calling super.

3. A factory function instead of a subclass

If the only thing a subclass would do is override the factory method, you don't need the subclass. Pass the factory in. In Java it's a Supplier<RecordParser>, in Python any callable, in TypeScript a function type. This is composition over inheritance applied to Factory Method, and it's usually the better default in modern code. The creator now looks a little like a Strategy holder, except that what it receives makes strategies rather than being one.

4. A registry (an open simple factory)

When the product is chosen by a runtime value, such as a file extension, a config string or a message type, a Map from key to factory function replaces the switch. New products register themselves, so the factory doesn't change when they're added. This is how plugin systems usually work.

The code group below shows variations 3 and 4 together. One Importer class takes a parser factory, and a registry maps file extensions to factories.

import java.util.*;
import java.util.function.Supplier;

record Row(String key, String value) {}

interface RowParser { Row parse(String line); }

final class Importer {
    private final Supplier<RowParser> parserFactory;      // the factory, injected
    Importer(Supplier<RowParser> parserFactory) { this.parserFactory = parserFactory; }

    List<Row> importAll(String text) {
        RowParser parser = parserFactory.get();
        List<Row> rows = new ArrayList<>();
        for (String line : text.strip().split("\n")) rows.add(parser.parse(line));
        return rows;
    }
}

final class ParserRegistry {
    private final Map<String, Supplier<RowParser>> byExtension = new HashMap<>();

    void register(String extension, Supplier<RowParser> factory) {
        if (byExtension.putIfAbsent(extension, factory) != null)
            throw new IllegalStateException("already registered: " + extension);
    }

    Supplier<RowParser> forFile(String fileName) {
        String ext = fileName.substring(fileName.lastIndexOf('.') + 1);
        Supplier<RowParser> factory = byExtension.get(ext);
        if (factory == null) throw new IllegalArgumentException("no parser for ." + ext);
        return factory;
    }
}

public class Main {
    public static void main(String[] args) {
        ParserRegistry registry = new ParserRegistry();
        registry.register("csv", () -> line -> { String[] p = line.split(","); return new Row(p[0], p[1]); });
        registry.register("tsv", () -> line -> { String[] p = line.split("\t"); return new Row(p[0], p[1]); });
        // A plugin added later registers itself: no existing code changes.
        registry.register("kv", () -> line -> { String[] p = line.split("="); return new Row(p[0], p[1]); });

        List<Row> rows = new Importer(registry.forFile("users.kv")).importAll("a=1\nb=2");
        if (!rows.equals(List.of(new Row("a", "1"), new Row("b", "2")))) throw new AssertionError(rows);
        try {
            registry.forFile("users.xml");
            throw new AssertionError("expected failure");
        } catch (IllegalArgumentException expected) { }
        System.out.println(rows);
    }
}
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import PurePath


@dataclass(frozen=True)
class Row:
    key: str
    value: str


RowParser = Callable[[str], Row]
ParserFactory = Callable[[], RowParser]


class Importer:
    def __init__(self, parser_factory: ParserFactory) -> None:
        self._parser_factory = parser_factory     # the factory, injected

    def import_all(self, text: str) -> list[Row]:
        parse = self._parser_factory()
        return [parse(line) for line in text.strip().splitlines()]


class ParserRegistry:
    def __init__(self) -> None:
        self._by_extension: dict[str, ParserFactory] = {}

    def register(self, extension: str) -> Callable[[ParserFactory], ParserFactory]:
        def decorator(factory: ParserFactory) -> ParserFactory:
            if extension in self._by_extension:
                raise ValueError(f"already registered: {extension}")
            self._by_extension[extension] = factory
            return factory
        return decorator

    def for_file(self, name: str) -> ParserFactory:
        ext = PurePath(name).suffix.lstrip(".")
        try:
            return self._by_extension[ext]
        except KeyError:
            raise ValueError(f"no parser for .{ext}") from None


registry = ParserRegistry()


@registry.register("csv")
def csv_parser() -> RowParser:
    return lambda line: Row(*line.split(",", 1))


@registry.register("kv")                       # a plugin added later
def kv_parser() -> RowParser:
    return lambda line: Row(*line.split("=", 1))


rows = Importer(registry.for_file("users.kv")).import_all("a=1\nb=2")
assert rows == [Row("a", "1"), Row("b", "2")]
try:
    registry.for_file("users.xml")
    raise AssertionError("expected failure")
except ValueError:
    pass
print(rows)
import assert from "node:assert/strict";

type Row = Readonly<{ key: string; value: string }>;
type RowParser = (line: string) => Row;
type ParserFactory = () => RowParser;

class Importer {
  constructor(private readonly parserFactory: ParserFactory) {}    // the factory, injected
  importAll(text: string): Row[] {
    const parse = this.parserFactory();
    return text.trim().split("\n").map(parse);
  }
}

class ParserRegistry {
  readonly #byExtension = new Map<string, ParserFactory>();

  register(extension: string, factory: ParserFactory): void {
    if (this.#byExtension.has(extension)) throw new Error(`already registered: ${extension}`);
    this.#byExtension.set(extension, factory);
  }

  forFile(name: string): ParserFactory {
    const ext = name.slice(name.lastIndexOf(".") + 1);
    const factory = this.#byExtension.get(ext);
    if (!factory) throw new Error(`no parser for .${ext}`);
    return factory;
  }
}

const split = (sep: string): ParserFactory => () => (line) => {
  const i = line.indexOf(sep);
  return { key: line.slice(0, i), value: line.slice(i + 1) };
};

const registry = new ParserRegistry();
registry.register("csv", split(","));
registry.register("kv", split("="));            // a plugin added later

const rows = new Importer(registry.forFile("users.kv")).importAll("a=1\nb=2");
assert.deepEqual(rows, [{ key: "a", value: "1" }, { key: "b", value: "2" }]);
assert.throws(() => registry.forFile("users.xml"), /no parser/);
console.log(rows);

5. Static factory methods

Joshua Bloch's Effective Java opens with "consider static factory methods instead of constructors". These are static methods like List.of(...), Integer.valueOf(int) or Optional.empty(). They are a different idea from the GoF pattern (no subclass decides anything), but they share the benefit of hiding the concrete class:

  • They have names. Duration.ofSeconds(5) reads better than new Duration(5, SECONDS).
  • They can return a cached instance. Integer.valueOf returns cached objects for values from -128 to 127.
  • They can return any subtype. EnumSet.noneOf(type) returns one of two internal implementations depending on how many constants the enum has (a single long bit vector for small enums, an array for large ones). The caller never knows.
  • They can do work a constructor can't. In TypeScript and JavaScript, constructors can't be async, so a static async create() that awaits a connection and then calls a private constructor is the standard workaround.

Python's equivalent is the @classmethod alternative constructor: dict.fromkeys, datetime.fromisoformat, int.from_bytes. These are named constructors that return an instance of cls, so they also work for subclasses.

Simple factory, factory method, abstract factory

Simple factoryFactory Method (GoF)Abstract Factory
ShapeOne function or static method with a switch or mapAn overridable method inside a class that also uses the productAn object with several creation methods
Who chooses the productThe factory, based on an argumentA subclass (or an injected function)The concrete factory object chosen by the client
ProductsOne kind, several implementationsOne kindA family of related kinds
ExtensionEdit the switch, or add to a registryAdd a subclassAdd a whole new factory class
Typical useParsing config strings into objectsFrameworks with overridable hooksSwapping a whole platform or theme

Simple factory isn't one of the 23 GoF patterns, but it's the most common in real code, and there's nothing wrong with it. When interviewers ask for "a factory", they usually mean a simple factory. Name it correctly, and mention the registry form if they push on open/closed.

Real-world uses

JDK

  • Iterable.iterator() is the canonical example. ArrayList, HashSet and TreeMap.keySet() each return their own iterator class, and the enhanced for loop only ever sees the Iterator interface. The collection is the creator, and each subclass decides the product.
  • java.util.concurrent.ThreadFactory is the function-object form: Executors.newFixedThreadPool(n, threadFactory) lets you decide how the pool's threads are created (names, daemon flag, priority) without subclassing the executor.
  • Static factories everywhere: List.of, Map.of, Optional.of, Integer.valueOf, EnumSet.noneOf, Path.of, Executors.newFixedThreadPool.
  • NumberFormat.getInstance(locale) and Calendar.getInstance() return locale-appropriate subclasses behind an abstract type.

Spring

  • @Bean methods in a @Configuration class are factory methods: the container calls them to obtain instances, and the method body decides the concrete type.
  • The FactoryBean<T> interface lets a bean's getObject() method produce the real object the container exposes, for complex construction that doesn't fit a constructor.

.NET

  • IHttpClientFactory.CreateClient(name) creates configured HttpClient instances so application code doesn't construct them directly.
  • DbProviderFactory.CreateConnection() and CreateCommand() return provider-specific objects (strictly, the provider factory as a whole is an Abstract Factory whose individual methods are factory methods).

Python

  • collections.defaultdict(list) takes a factory function and calls it whenever a missing key is accessed: the factory-function variation in the standard library.
  • pathlib.Path(...) returns a PosixPath or WindowsPath depending on the operating system, so constructing the abstract-looking class actually gives you a platform-specific subclass.
  • Alternative constructors as class methods: datetime.fromtimestamp, dict.fromkeys, int.from_bytes.

Node and the browser

  • crypto.createHash("sha256"), http.createServer() and net.createConnection() are simple factories that hide the concrete class.
  • document.createElement("table") returns an HTMLTableElement. The tag name chooses the concrete element class.

React

  • React.createElement(type, props, ...children) (what JSX compiles to in the classic runtime) is a factory function. You never instantiate an element class yourself.

When NOT to use it, and the costs

Factory Method has a modest cost, but it's real: an extra class per variant and an extra hop when reading code. Don't pay it when:

  • There is one product and no foreseeable second. new CsvParser() is clearer than a creator hierarchy with one subclass. Add the indirection when the second format arrives. The change at that point is small, which is exactly why you don't need to do it in advance. See over-patterning.
  • The subclass would exist only to override the factory method. Pass a function instead (variation 3). A class hierarchy that mirrors the product hierarchy one-to-one, sometimes called parallel hierarchies, is the classic cost of the inheritance form. Each new product means two new classes.
  • The choice depends on runtime data. Subclasses are fixed at compile time. If the format is known only when a file arrives, use a registry or simple factory. Creating a new subclass per value doesn't make sense.
  • Construction is trivial and the type is stable. Value objects, DTOs and records don't need factories.
  • Your language already gives you the hook. In Python, a class is a callable that creates instances, so you can pass CsvParser itself as the factory. In TypeScript, a constructor type (new () => RecordParser) can serve the same purpose.

Costs to name:

CostWhy it matters
Parallel class hierarchiesEvery product needs a creator subclass in the GoF form
IndirectionReaders must find which subclass is in play to know which product is created
Inheritance couplingCreators are subclasses, with the usual fragile-base-class risks
Harder runtime selectionSubclasses are chosen once, so runtime switching needs a registry anyway
  • Abstract Factory. Creates families of related products through several methods on one factory object, chosen by composition. Its methods are frequently implemented as factory methods. Rule of thumb: one product varies, use Factory Method; several products must vary together, use Abstract Factory.
  • Template Method. Factory Method is very often called from a template method (as importFile calls createParser). The difference is purpose: Template Method varies a step of an algorithm; Factory Method varies which object is created.
  • Prototype. Avoids the creator subclass entirely: the creator holds a prototype object and clones it. It's useful when the products are configured at runtime rather than being distinct classes.
  • Builder. Focuses on how one complex object is assembled step by step, not on which class is created. A factory method can return a builder, and a builder's build() is sometimes a factory method.
  • Strategy. The injected-function variation resembles Strategy. The difference is what's injected: a strategy is the behaviour, while a factory produces an object. Use a factory when each run needs a fresh product (parsers with per-file state, for example).
  • Singleton. A factory method may return a shared instance instead of a new one. That's an implementation detail hidden from the client, which is one of the advantages of factories over constructors.
  • Dependency Injection. Containers are generalised factories, and @Bean methods are literally factory methods. When creation is just "wire the right implementation in", DI usually replaces hand-written factories.

The smell that suggests it

  • A conditional on type inside a workflow. if (format.equals("csv")) new CsvParser() else if ... embedded in a method that does other work. If the same conditional appears in more than one method, the smell is strong.
  • A class you'd like to reuse, except for one new. "This report generator is perfect, except it always writes PDF." The new PdfWriter() buried inside is the line to turn into a factory method.
  • Tests that can't substitute an internal collaborator because the class constructs it directly.
  • Framework code that must create objects whose types belong to the application. The framework can't know application classes, so it defines an overridable or injectable creation hook.

The refactoring is Replace Constructor Call with Factory Method. Extract the new into a protected method returning the interface, then move each conditional branch into its own subclass (or registry entry).

Interview questions

  1. "What's the difference between Factory Method and a simple factory?" A simple factory is a function that picks a class with a switch or map. Factory Method is an overridable creation method inside a class that also uses the product as part of a larger operation. The simple factory varies by argument, Factory Method varies by subclass.
  2. "Factory Method or Abstract Factory?" Factory Method when one product type varies. Abstract Factory when several related products must vary together and stay consistent (a whole UI theme, a whole database provider).
  3. "How does Factory Method support the open/closed principle?" The workflow in the creator never changes when a new product is added. You add a new product class and a new creator subclass (or registry entry). Existing tested code is untouched.
  4. "Isn't a switch in a factory still a violation of open/closed?" Yes, mildly, though it confines the violation to one place, which is often acceptable. To remove it, use a registry where products register themselves, or Java's ServiceLoader for plugins.
  5. "Why would you prefer a static factory method to a constructor?" It has a name, can cache and reuse instances, can return a subtype or a different implementation per input, and can perform work a constructor shouldn't (or, in TypeScript, can't, such as awaiting). The downsides: classes with only private constructors can't be subclassed, and static factories are harder to find in docs than constructors.
  6. "Give an example of Factory Method in the JDK." Iterable.iterator(): each collection returns its own iterator implementation and client code only knows Iterator. ThreadFactory is the function-object form.
  7. "Your factory method needs a runtime argument to choose the product. What changes?" You've moved toward a parameterised factory or simple factory. Consider a Map<String, Supplier<Product>> registry, and validate unknown keys with a clear error.
  8. "How would you write this without inheritance?" Inject a factory: Supplier<T> in Java, a callable in Python, a () => T in TypeScript. The creator keeps its workflow and the caller decides the product. Interviewers like to hear that you know composition can replace the subclass.
  9. "In a parking lot design, where might a factory method appear?" Creating the right Spot or Ticket subtype by vehicle type, or a PricingPolicy per lot type. Mention that if vehicle types are fixed and few, a simple factory or even an enum with a creation method is enough. See the parking lot case study.

Further reading