Factory Method

Let a base class run a workflow but leave one step, creating an object, to subclasses that decide which class it is.

Description

A factory method is an overridable method whose only job is to create an object, such as createChannel(). The base class (the creator) calls it in the middle of its own logic and works with the result through an interface.

Each subclass overrides the factory method to return a different product: an email channel, an SMS channel. The shared workflow, greeting and delivering, is written once in the base class and never repeated.

In everyday TypeScript the same idea often appears as a plain factory function (createChannel(kind)), which is the lighter choice when you don't need the inheritance.

Class diagram

uses«create»«abstract»Notifier+ notify(user, text)# createChannel(): Channel«interface»Channel+ deliver(user, text)SmsNotifier# createChannel()EmailNotifier# createChannel()EmailChannel+ deliver(user, text)SmsChannel+ deliver(user, text)

Factory Method pattern class diagram

  1. Abstract class Notifier with + notify(user, text), # createChannel(): Channel.
  2. Interface Channel with + deliver(user, text).
  3. Class SmsNotifier with # createChannel().
  4. Class EmailNotifier with # createChannel().
  5. Class EmailChannel with + deliver(user, text).
  6. Class SmsChannel with + deliver(user, text).
  7. Notifier uses Channel.
  8. SmsNotifier extends Notifier.
  9. EmailNotifier extends Notifier.
  10. EmailChannel implements Channel.
  11. SmsChannel implements Channel.
  12. EmailNotifier creates EmailChannel.

Sequence diagram

AppEmailNotifierEmailChannel1. notify(kim, text)2. createChannel()3. new EmailChannel()4. deliver(kim, "Hi Kim, …")5. "email to kim@…"6. result

Factory Method pattern sequence diagram

  1. App → EmailNotifier: notify(kim, text).
  2. EmailNotifier → EmailNotifier: createChannel().
  3. EmailNotifier → EmailChannel: new EmailChannel().
  4. EmailNotifier → EmailChannel: deliver(kim, "Hi Kim, …").
  5. EmailNotifier receives ""email to kim@…"" back from EmailChannel.
  6. App receives "result" back from EmailNotifier.

TypeScript example

A notifier base class with one shared workflow. EmailNotifier and SmsNotifier only override createChannel(), the factory method. The diagram shows the creates link for email; SMS works the same way.

factory-method.ts
// Factory Method: the base class runs the workflow; subclasses decide
// which channel object gets created.

interface User {
  name: string;
  email: string;
  phone: string;
}

// Product
interface Channel {
  deliver(user: User, text: string): string;
}

class EmailChannel implements Channel {
  deliver(user: User, text: string): string {
    return `email to ${user.email}: ${text}`;
  }
}

class SmsChannel implements Channel {
  deliver(user: User, text: string): string {
    const short = text.length > 40 ? `${text.slice(0, 39)}…` : text;
    return `sms to ${user.phone}: ${short}`;
  }
}

// Creator: shared workflow, one overridable creation step
abstract class Notifier {
  protected abstract createChannel(): Channel; // the factory method

  notify(user: User, text: string): string {
    const channel = this.createChannel();
    return channel.deliver(user, `Hi ${user.name}, ${text}`);
  }
}

// Concrete creators
class EmailNotifier extends Notifier {
  protected createChannel(): Channel {
    return new EmailChannel();
  }
}

class SmsNotifier extends Notifier {
  protected createChannel(): Channel {
    return new SmsChannel();
  }
}

export function demo(): string[] {
  const kim: User = { name: "Kim", email: "kim@example.com", phone: "+46 70 000 00 00" };
  const message = "your order has shipped and arrives on Friday.";
  const notifiers: Notifier[] = [new EmailNotifier(), new SmsNotifier()];
  return notifiers.map((n) => n.notify(kim, message));
}

When to use it

Use it when

  • A base class has a fixed workflow, and only the type of one object in it varies.
  • Frameworks and libraries that let users plug in their own classes by subclassing.
  • You want to keep new SomeConcreteClass() out of the code that uses the object.

Avoid it when

  • There's no shared workflow, only object creation. A factory function or a lookup map is simpler.
  • You'd create a subclass just to change one constructor argument. Pass the argument instead.
  • Composition fits better: pass the channel in (dependency injection) rather than subclassing to choose it.

Pitfalls

  • A parallel class hierarchy: every new product needs a new creator subclass. If that keeps happening, inject the product or a factory function instead.
  • Calling the factory method from the base-class constructor, before the subclass is fully set up.
  • Deep inheritance trees that are hard to follow. Keep it to one level of creator subclasses.

Alternatives

Factory function

Choose it when you only need "give me the right object for this input": const channelFor = (kind) => kind === "sms" ? new SmsChannel() : new EmailChannel().

Abstract Factory

Choose it when several related objects must be created together as a consistent family.

Strategy

Choose it when you can pass the varying object in from outside instead of subclassing to create it.

Template Method

Choose it when more than one step of the workflow varies, not just object creation.