Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 57 ยท Creational Patterns

Factory Method

Learn the Factory Method design pattern: creator and product hierarchies, parameterized factories, static factory methods and when to use each.

The Factory Method pattern defines a method for creating an object, but lets subclasses (or a lookup table) decide which concrete class to instantiate. The code that uses the object talks only to an abstract type and never writes new ConcreteThing() itself. That keeps the using code stable while the set of concrete classes grows.

Imagine an app that sends notifications. At first it only sends email, and new EmailNotification() appears in a dozen places. When SMS and push arrive, every one of those places needs an if chain. Factory Method moves the "which class?" decision into one place and gives callers a single, clean entry point. It applies the Open/Closed Principle and the Dependency Inversion Principle to object creation.

Four roles

Product The abstract type callers use.
Concrete product Email, SMS, push implementations.
Creator Declares the factory method.
Concrete creator Overrides it to build one product.

The creator's other code works only with the Product type.

1 / 2

The classic structure

In the textbook version there are two parallel hierarchies. The product hierarchy contains what gets created; the creator hierarchy contains the factories. The creator has some business operation that needs a product, and a factory method (often abstract) that subclasses override.

classDiagram
    class Notification {
        <<interface>>
        +send(message)
    }
    class EmailNotification
    class SmsNotification
    class NotificationService {
        +createNotification()* Notification
        +notify(message)
    }
    class EmailService
    class SmsService
    Notification <|.. EmailNotification
    Notification <|.. SmsNotification
    NotificationService <|-- EmailService
    NotificationService <|-- SmsService
    NotificationService ..> Notification : creates

The creator's notify() calls createNotification(); each subclass decides which product that is.

The important line is in notify: it calls this.createNotification() and uses the result as a plain Notification. It has no idea whether that is email or SMS.

JS Factory Method with creator subclasses

Press Run (or Ctrl + Enter) to see the console output here.

No output.

sendWelcome works with any NotificationService. To add push notifications you write PushNotification and PushService, and no existing class changes. The price is two new classes per product, which is why this form is best when the creator subclasses carry real behavior of their own, such as a PushService that also needs a device registry.

Parameterized factories and registries

Often a whole parallel hierarchy of creators is more ceremony than you need. A parameterized factory method takes a key (a string, an enum) and returns the right product. In JavaScript and Python, a lookup table of constructors is the most idiomatic version, and it can be extended at run time without touching an if chain.

JS A parameterized factory with a registry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The trade-off is that the key is a string, so a typo becomes a run-time error rather than a compile error. In Java and C++ you would usually replace the string with an enum, and the compiler can then check that every case is handled.

Static factory methods

Not every factory needs a class hierarchy. A static factory method is simply a named static method that returns an instance, used instead of (or alongside) a constructor. This is not the same as the GoF pattern, but it is closely related and extremely common. Java's List.of(...), LocalDate.of(...) and Integer.valueOf(...) are examples; Python's datetime.fromtimestamp and dict.fromkeys are class methods used the same way.

Static factories have real advantages over constructors:

  • They have names: Money.fromCents(250) says more than new Money(250).
  • They can return a cached or shared instance instead of always building a new one.
  • They can return a subtype or different classes depending on the input.
  • They can validate and refuse to build an invalid object while keeping the constructor private.
JS Named static factories

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three different constructors would have been impossible in one signature (all take a number), so the names carry the meaning. Java and C++ face the same limit, since both use overloads by type rather than by meaning.

When to use Factory Method

Reach for it when:

  • Your code needs to create objects but should not hard-code the concrete class.
  • The exact class depends on configuration, input, environment or a subclass.
  • Creation involves non-trivial setup that you want in one place.
  • You want to make testing easier by substituting fake products.

Skip it when a plain constructor is clear and there is only ever one class. Wrapping new User(name) in a UserFactory.createUser(name) that does nothing else adds a layer with no benefit, a classic premature abstraction.

Limitations

  • Subclass explosion. The classic form needs one creator subclass per product, so a small change can double the number of classes. Parameterized factories and registries (above) avoid this.
  • Extra indirection. Readers must follow a call through the creator to find which class is built.
  • Client changes. If the client picks the creator, adding a product can still mean editing client code unless the choice comes from configuration.

Compare the neighbors. Factory Method creates one product and varies it by subclass or key. The next pattern, Abstract Factory, creates families of related products that must go together. A Builder assembles one complex object step by step. Keep these three apart in your mind and many interview questions become easy.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main idea of the Factory Method pattern?

    Factory Method defines an overridable creation method so that the client code works with an abstract product type.
  2. 2. In the classic structure, which role contains the factory method?

    The creator declares the factory method, and concrete creators override it to return a particular concrete product.
  3. 3. What is a benefit of a static factory method such as Money.fromCents(250)?

    Named factories explain intent, can return cached or different types, and keep validation in one place.
  4. 4. What is the drawback of a parameterized factory that uses string keys?

    Strings are not checked by the compiler. Enums or constants turn many such mistakes into compile-time errors.
  5. 5. How does Factory Method differ from Abstract Factory?

    Abstract Factory groups several factory methods so that a set of related products is created consistently.

Summary

  • Factory Method moves "which class do I instantiate?" out of the client into an overridable method.
  • Classic form: product hierarchy plus creator hierarchy; the creator's logic uses only the abstract product.
  • Parameterized factories and registries choose a product by key and extend without edits.
  • Static factory methods give constructors names, validation and flexibility.
  • Do not add a factory when a simple constructor is enough.

Next lesson: Abstract Factory.