Skip to content

Factory Method: Let Subclasses Decide Which Object to Create

Learn the Factory Method pattern through a payment reconciliation job that lets each acquirer subclass pick its own settlement file parser.

11 min readDesign patternCreational

Define a method for creating an object, and let subclasses, or a default hook they can override, decide which concrete class to instantiate. The code that uses the object depends only on its interface, never on the concrete class.

Factory Method is one of the first creational patterns interviewers ask about, and it is easy to describe badly. People often confuse it with any function that returns a new object. The real pattern is narrower. A base class owns an algorithm that needs an object, and it asks an overridable method to supply that object. This guide uses one scenario throughout: a nightly reconciliation job at a payments company. You will see the problem, the structure, pseudocode, and runnable TypeScript, Python and PHP that all solve the same case.

The problem

A situation where the obvious design starts to hurt.

Kestrel Pay settles card payments through three acquiring banks. Every night a reconciliation job downloads each acquirer's settlement file, about 40,000 lines in total, and checks every line against the amounts Kestrel expected to receive. Mismatches go to the finance team by 7 a.m.

The matching logic is identical for every acquirer: read a line, turn it into a reference and an amount in cents, look up the expected amount, record any difference. The only thing that varies is the file format. Northbank sends comma-separated lines like NB-77,4999. Paylane sends fixed-width records where the first 10 characters are the reference and the next 12 are a zero-padded amount.

Today the job has a single run(acquirer) method with a switch on the acquirer name inside the loop, and each branch contains its own parsing code. The team has just signed a fourth acquirer, Corvid, which sends semicolon-separated lines with amounts in decimal euros. Adding it means editing the shared loop again, retesting all three existing branches, and risking a broken Paylane parse because someone touched a variable two branches up. The matching code and the format details are tangled together, and every new acquirer makes the method longer.

The solution

What the pattern proposes.

Separate the part that varies, which parser to use, from the part that stays fixed, the matching loop. Introduce a SettlementParser interface with one method, parse(line), that returns a Settlement with a reference and an amount in cents. Each format gets its own class: NorthbankCsvParser and PaylaneFixedWidthParser.

Then turn the job into an abstract creator, ReconciliationJob. Its run method contains the matching loop and calls this.createParser() once at the start. createParser is the factory method. It is declared abstract, so each subclass, NorthbankReconciliationJob and PaylaneReconciliationJob, overrides it and returns the parser it needs. run never mentions a concrete parser class.

Adding Corvid now means writing a CorvidSemicolonParser and a CorvidReconciliationJob whose createParser returns it. The loop is untouched and the existing acquirers are not retested for regressions caused by the change.

The factory method does not have to be abstract. If most acquirers used plain CSV, createParser could return NorthbankCsvParser by default and only the odd ones would override it. That default version is a hook: the base class works on its own, and subclasses step in only when they need something different.

An everyday analogy

The same idea, outside software.

Think of a sandwich chain whose head office writes one assembly routine for every branch: slice the bread, add the filling, toast for two minutes, wrap, hand over. The routine never says which bread to use. Each branch decides that step for itself, so the coastal branch uses its local sourdough and the airport branch uses a long-life roll. Staff follow the same routine everywhere, and opening a branch with a new bakery does not require rewriting the routine, only deciding what goes in the bread step.

Structure

The pieces and how they relate.

ReconciliationJob runs the matching loop and calls createParser(); each subclass returns its own SettlementParser.NightlyScheduler calls ReconciliationJob (run(lines, expected)). ReconciliationJob calls SettlementParser (parse(line)). NorthbankReconciliationJob inherits from ReconciliationJob. PaylaneReconciliationJob inherits from ReconciliationJob. NorthbankCsvParser implements SettlementParser. PaylaneFixedWidthParser implements SettlementParser. NorthbankReconciliationJob creates NorthbankCsvParser. PaylaneReconciliationJob creates PaylaneFixedWidthParser.NightlySchedulerpicks a job peracquirer«abstract»ReconciliationJobrun(); abstract createParser()«interface»SettlementParserparse(line): SettlementNorthbankReconciliationJobcreateParser()PaylaneReconciliationJobcreateParser()NorthbankCsvParsercomma-separatedlinesPaylaneFixedWidthParser10 + 12 char fieldsrun() names noparseronly the interfacerun(lines, expected)parse(line)
ReconciliationJob runs the matching loop and calls createParser(); each subclass returns its own SettlementParser.

Participants

Product: SettlementParser
The interface every created object satisfies. The creator only ever talks to this type.
Concrete products: NorthbankCsvParser, PaylaneFixedWidthParser
Each knows one acquirer's file format and turns a raw line into a Settlement.
Creator: ReconciliationJob
Holds the business logic (the matching loop) and declares the factory method createParser(). It may be abstract or provide a default product.
Concrete creators: NorthbankReconciliationJob, PaylaneReconciliationJob
Override createParser() to return the right concrete parser. They add nothing else.
Client: NightlyScheduler
Chooses which concrete job to run for each acquirer and calls run(). It is the only place that knows the full list of acquirers.

Pseudocode

The solution to the scenario, language-neutral.

interface SettlementParser
    method parse(line): Settlement

class NorthbankCsvParser implements SettlementParser
    method parse(line)
        reference, amount = split line on ","
        return Settlement(trim(reference), toInt(amount))

class PaylaneFixedWidthParser implements SettlementParser
    method parse(line)
        return Settlement(trim(line[0..10]), toInt(line[10..22]))

abstract class ReconciliationJob
    abstract method createParser(): SettlementParser   // the factory method

    method run(lines, expected): list of string
        parser = createParser()
        mismatches = []
        for each line in lines
            s = parser.parse(line)
            want = expected[s.reference] or none
            if want != s.amountCents
                add "{s.reference}: expected {want}, got {s.amountCents}" to mismatches
        return mismatches

class NorthbankReconciliationJob extends ReconciliationJob
    method createParser()
        return new NorthbankCsvParser()

class PaylaneReconciliationJob extends ReconciliationJob
    method createParser()
        return new PaylaneFixedWidthParser()

// client
print new NorthbankReconciliationJob().run(northbankLines, expected)
print new PaylaneReconciliationJob().run(paylaneLines, expected)

The code

The same solution in TypeScript, Python and PHP.

interface Settlement {
  reference: string;
  amountCents: number;
}

interface SettlementParser {
  parse(line: string): Settlement;
}

class NorthbankCsvParser implements SettlementParser {
  parse(line: string): Settlement {
    const [reference, amount] = line.split(",");
    return { reference: reference.trim(), amountCents: Number(amount) };
  }
}

class PaylaneFixedWidthParser implements SettlementParser {
  parse(line: string): Settlement {
    return {
      reference: line.slice(0, 10).trim(),
      amountCents: Number(line.slice(10, 22)),
    };
  }
}

abstract class ReconciliationJob {
  // The factory method: subclasses decide which parser to create.
  protected abstract createParser(): SettlementParser;

  run(lines: string[], expected: Map<string, number>): string[] {
    const parser = this.createParser();
    const mismatches: string[] = [];
    for (const line of lines) {
      const s = parser.parse(line);
      const want = expected.get(s.reference);
      if (want !== s.amountCents) {
        mismatches.push(`${s.reference}: expected ${want ?? "none"}, got ${s.amountCents}`);
      }
    }
    return mismatches;
  }
}

class NorthbankReconciliationJob extends ReconciliationJob {
  protected createParser(): SettlementParser {
    return new NorthbankCsvParser();
  }
}

class PaylaneReconciliationJob extends ReconciliationJob {
  protected createParser(): SettlementParser {
    return new PaylaneFixedWidthParser();
  }
}

const expected = new Map<string, number>([
  ["NB-77", 4999],
  ["NB-78", 1000],
  ["PL-0000042", 12500],
]);

console.log(new NorthbankReconciliationJob().run(["NB-77,4999", "NB-78,1200"], expected));
// [ 'NB-78: expected 1000, got 1200' ]
console.log(
  new PaylaneReconciliationJob().run(
    ["PL-0000042000000012500", "PL-0000043000000000999"],
    expected,
  ),
);
// [ 'PL-0000043: expected none, got 999' ]

When to use it

Situations where it pays off.

  • A class runs a fixed algorithm but one step needs an object whose concrete type varies by context.

    The factory method isolates that single decision. The algorithm stays in one place, and each variant only answers the question of which object to build.

  • You expect new variants to appear, like new acquirers, file formats or storage backends.

    A new variant is a new pair of classes rather than an edit to shared code, so existing variants keep working without being touched.

  • You ship a library or framework and want users to plug in their own component without forking your code.

    Users subclass your creator and override one method. Your core logic calls their object through the interface you defined.

  • Most callers want a sensible default, but a few need something different.

    A non-abstract factory method acts as a hook: it returns the default product, and only the special cases override it.

  • Tests need to swap a real dependency for a fake inside a class you cannot easily inject into.

    A test subclass can override the factory method to return a stub, leaving the logic under test unchanged.

How to implement it

Steps to introduce it in existing code.

  1. Find the place where the code picks a concrete class, usually a new inside a switch or if-chain, and confirm the surrounding logic is the same for every branch.

  2. Extract a product interface that covers what the surrounding logic actually uses. For Kestrel that is a single parse(line) method.

  3. Move each branch's object-specific code into its own class that implements the interface.

  4. In the creator, add a factory method that returns the interface type, and replace the switch with one call to it. Make it abstract, or give it a default product if one variant is the common case.

  5. Create one subclass per variant that overrides only the factory method.

  6. Move the remaining choice of variant to the edge of the system, such as the scheduler or a configuration lookup, so the creator never sees the full list.

  7. Delete the old switch and check that no code outside the concrete creators refers to concrete products.

Pros and cons

What you gain and what you pay.

Pros

  • The creator's logic depends only on the product interface, so it can be read and tested without knowing any concrete format.
  • Open/closed in practice: adding a variant means adding classes, not editing the shared algorithm.
  • Each format lives in one small class, which keeps single responsibility clear and makes parsers easy to unit test in isolation.
  • A default implementation gives you a cheap extension point that costs nothing for callers who never override it.

Cons

  • You get a creator subclass for every product, which can feel like ceremony when the subclass is three lines long.
  • The variant is fixed by inheritance at compile time. If you need to choose the parser at runtime from configuration, passing a parser or a factory object in is often simpler.
  • Deep creator hierarchies get hard to follow, especially when subclasses override both the factory method and parts of the algorithm.
  • Readers new to the code have to jump from run() to a subclass to find out which object is actually used.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

Is any function that returns a new object a Factory Method?

No. A standalone function or static method that picks a class from an argument is usually called a simple factory. Factory Method specifically means an overridable method on a creator class, called by the creator's own logic, so that subclasses change which object that logic works with.

How is Factory Method different from Abstract Factory?

Factory Method relies on inheritance: a subclass overrides one creation method used by the base class's algorithm. Abstract Factory relies on composition: you pass in an object that has several creation methods producing a family of related products. If Kestrel needed a matching parser, fee calculator and file fetcher per acquirer, that family would point toward Abstract Factory.

Does the factory method have to be abstract?

No. It can return a default product, which turns it into a hook. The creator then works on its own, and subclasses override the method only when they need a different product. This is common in frameworks that want a sensible default with an escape hatch.

Why not just pass the parser into the job's constructor?

That is often the better choice, especially when the parser is chosen at runtime or you want to avoid one job subclass per parser. Factory Method fits when the creator is meant to be subclassed anyway, when a framework controls construction, or when the product must be created lazily inside the algorithm. Being able to name this trade-off is a strong interview signal.

Should the factory method return a new object every call?

Not necessarily. The contract is that it returns something satisfying the product interface. It may return a new instance, a cached one or a pooled one. In the Kestrel job it is called once per run, so a fresh parser each time is simplest and keeps runs independent.

Next guide2 of 5 · Creational patternsAbstract Factory: Create Families of Objects That Belong TogetherRead the next one