Skip to content
DiaGO

Factory Method

Let subclasses decide which concrete product to create. A creational pattern that keeps client code closed against new product types.

Open this example in Studio

Intent

Factory Method defines an interface for creating an object, but lets subclasses decide which class to instantiate. The GoF book also calls it virtual constructor: the creator invokes a method it declares but does not finish, and the actual new happens in a subclass override.

The problem it solves is coupling, not construction. A class that writes new EmailChannel() inline is welded to that concrete class. If the instantiation sits inside a larger algorithm — a send workflow, an import pipeline — then supporting a new variant means editing that algorithm. Factory Method extracts the one line that varies into an overridable seam, so the algorithm can stay put while the product changes underneath it.

Structure

The pattern has four roles:

  • Product — the interface every created object implements.
  • ConcreteProduct — a specific implementation of Product.
  • Creator — declares the factory method returning a Product, and usually calls it from template logic that does real work with the result.
  • ConcreteCreator — overrides the factory method to return one specific ConcreteProduct.

In a class diagram the shape is two parallel generalization hierarchies side by side. On the left, an abstract Creator with the factory method in italics, and ConcreteCreators beneath it connected by hollow-triangle arrows. On the right, the Product interface with ConcreteProducts realizing it. A dashed dependency arrow runs from each ConcreteCreator to the ConcreteProduct it instantiates; the Creator itself refers only to the Product interface. That visual symmetry is the pattern's signature — and, as we will see, also its main cost.

Worked example: notifications

A booking platform sends notifications over several channels. The delivery steps are identical — resolve the recipient, render the message, deliver, record the outcome — but the transport differs.

interface NotificationChannel {
  deliver(recipient: string, body: string): Promise<void>;
}
 
class EmailChannel implements NotificationChannel {
  async deliver(recipient: string, body: string): Promise<void> {
    // SMTP call
  }
}
 
class SmsChannel implements NotificationChannel {
  async deliver(recipient: string, body: string): Promise<void> {
    // SMS gateway call
  }
}
 
abstract class Notifier {
  // Template logic: fixed workflow, variable product.
  async send(recipient: string, message: string): Promise<void> {
    const body = this.render(message);
    const channel = this.createChannel(); // the factory method
    await channel.deliver(recipient, body);
    this.audit(recipient);
  }
 
  protected abstract createChannel(): NotificationChannel;
 
  protected render(message: string): string {
    return message.trim();
  }
 
  private audit(recipient: string): void {
    // write delivery record
  }
}
 
class EmailNotifier extends Notifier {
  protected createChannel(): NotificationChannel {
    return new EmailChannel();
  }
}
 
class SmsNotifier extends Notifier {
  protected createChannel(): NotificationChannel {
    return new SmsChannel();
  }
}

send() never names a concrete channel. It works entirely against the NotificationChannel interface, which is dependency inversion in miniature: the high-level workflow depends on an abstraction, and the choice of implementation is pushed down to a subclass.

Adding push notifications means writing PushChannel and PushNotifier — two new files, zero edits to existing ones. That is the Open-Closed Principle made mechanical: the system is open to new product types through subclassing and closed against modification of the tested workflow.

Factory Method vs "a factory"

Here the vocabulary gets muddy, and it is worth being honest about it. What most codebases call a factory is a standalone function or static method with a switch:

function createChannel(kind: "email" | "sms"): NotificationChannel {
  switch (kind) {
    case "email":
      return new EmailChannel();
    case "sms":
      return new SmsChannel();
  }
}

This is usually called Simple Factory, and it is not the GoF pattern — there is no creator hierarchy and no inheritance. It is also, frequently, the right tool. One function is easier to read than four classes.

Simple FactoryGoF Factory Method
MechanismFunction or static method with a conditionalAbstract method overridden in subclasses
Adding a productEdit the switch (one known place)Add a subclass (no edits)
Best fitCreation is the only thing that variesCreation varies together with other behavior

The heuristic — and it is a heuristic, not a rule — is that Factory Method earns its keep when creation varies along the same axis as other behavior. If EmailNotifier also needs its own render() (HTML instead of plain text), the subclass was going to exist anyway, and hanging the factory method on it costs nothing. If the subclasses would exist only to host a one-line createChannel(), a simple factory is the cleaner design.

Costs

The main cost is the parallel class hierarchy: every ConcreteProduct tends to drag a ConcreteCreator into existence, roughly doubling the class count along that axis. Readers must now trace an override to find out what actually gets built, where a simple factory shows it in one screen.

Common misapplications:

  • A factory for a Product with exactly one implementation — pure ceremony until a second implementation is real, not hypothetical.
  • A creator hierarchy deeper than the products justify, such as three layers of abstract notifiers over two channels.
  • Simple factories relabeled as the pattern, which hides the fact that the switch still has to be edited for each new product.

Reach for it

  • A workflow must create objects whose concrete type it cannot know in advance
  • Each product variant already needs its own subclass for other behavioral differences
  • You want new product types added without touching tested client code

Avoid it

  • There is only one concrete product and a second is speculative
  • Creation is the only thing that varies between variants
  • A one-line factory function would be understood faster than a class hierarchy

Factory Method is a creational counterpart to behavioral patterns like Observer: both replace a hard-coded reference with an abstraction so that one side of the relationship can grow without the other noticing.

Practice

Build a report export feature for a library system. Define a Renderer product with a render(rows) method, and CsvRenderer and PdfRenderer concrete products. Write an abstract ReportExporter creator whose export() template fetches loan records, calls createRenderer(), and writes the result to disk. Then: (1) add JSON export without editing any existing class; (2) rewrite the whole thing as a single simple-factory function; (3) in one paragraph, decide which version this feature should actually ship with, and defend the choice using the creation-varies-with-behavior heuristic.