factory method
Create objects in a separate operation so that subclasses can override the way they're created.
The factory-method design pattern.
PNG
SVG
The factory method Design Pattern
Frequency
Complexity

The Factory Method may be the most frequent design pattern you will see during your career as a software developer.

This is mainly due to two of its main characteristics:

  1. It solves a widespread use case. This pattern separates the logic to create an object from the place where the object will actually be instantiated.
  2. It's straightforward to implement. To implement a Factory Method, you only need a few interfaces and one or two implementation classes.

To understand how this pattern works, let's look at some of its most prominent use cases.

Extending an existing system

Today, there is often no need to reinvent everything from scratch, as developers can choose from various frameworks and libraries.

These frameworks are usually closed systems, but they often provide base classes developers can subclass to add their custom implementation.

Suppose we're building an application based on an external GUI framework. This framework provides a base class MenuItem representing an entry in our application's main menu. When clicking on this menu item, an Action object containing the MenuItem's logic is created, stored in an undo stack (for later undo/redo operations), and finally executed.

A framework providing base classes for menu items and actions.
A framework provides a base class for menu items.
Clicking on a menu item will execute an action.

This Action class works as an extension point. We need to subclass it for every application-specific menu action in our application. But one problem we face with this approach is that the owning MenuItem does not know how our Action object should be created since our subclass is not part of the framework.

This is where the Factory Method pattern comes into play: The MenuItem class defines a method - createAction - which we have to override in a subclass to instantiate our custom Action.

A custom menu item implementation provides a factory method to create a custom action.
Extending the framework with custom implementations.

And that is already the quintessence behind the pattern: By overriding the factory method, we define how our objects are created, but the construction process itself is deferred and controlled by the framework. The framework doesn't even need to know the concrete type of the objects it creates as long as they conform to the required interface.

Ok, but we're not done yet, let's have a look at some more use cases for the Factory Method pattern.

Flexibility

So far, we have used subclassing to implement our factory method. By declaring different subclasses, we can configure our system at compile time.

But we can even go one step further and replace our factory implementations during runtime. We could, for instance, read from an external configuration file which factory method to use. Our application logic would then instantiate the corresponding object we later use to create products of a specific type. In that way, our system is highly flexible. The runtime configuration option gives us complete control over all object creations - even after the application has already started!

However, be careful to not overuse this strategy: This approach can quickly lead to overcomplicated systems where you spend more time editing cryptic XML configuration files than writing actual code - in most cases, not a good trade.

Reduce Coupling

Another noteworthy application of the factory method - perhaps one of its most valuable benefits - is its ability to reduce coupling.

Coupling describes how strongly two components or classes are connected and dependent on each other. A high degree of coupling between two elements means that they are strongly related and heavily interact with each other. This is problematic as changes must often be propagated to all coupled counterparts, resulting in increased maintenance effort. Strongly coupled systems also lose some flexibility because one part cannot easily be changed without affecting others.

To understand how class coupling emerges, we must look at how most OOP languages create objects. Often, calling 'new' on a type is all we have to do. This executes the class constructor and instantiates a new object of the given type. What's important here is that when calling the constructor, we have to specify the concrete type of an object. But this also creates a direct and strong dependency between our two types: The one we create (the Product) and the one where the actual call is made (the Client).

A Client class creating a Product.
Creating objects directly results in strong coupling between classes.

If our Product is just a simple object, that's not so much of a concern. But it gets worse if it is part of a complex inheritance hierarchy. E.g., if one of its base classes contains system-specific logic to access a file or network resources, our Client would also depend on these implementations.

As we know, using interfaces instead of implementations is a good way of reducing dependencies. We could extract all system-specific code into separate libraries, letting the components communicate only through interfaces.

But the major problem with interfaces is that they cannot be instantiated -most languages do not support calling new on an interface.

And again, that's where our factory method comes into play: Instead of constructing objects directly, we delegate the creation to a Factory Method returning only an interface. The coupling exists only between our factory implementation and the Product, but the dependency between Client and Product is successfully removed.

A client uses a factory method to create a product.
Using a factory method to reduce the coupling between Client and ConcreteProduct

Notice that in the diagram, there is no direct connection between Client and ConcreteProduct, and hence also no coupling between them. If necessary, they could even be located in separate modules.

We also did not implement the factory method directly in the Client, but instead defined a separate Factory interface. Some may say this is a different design pattern, the Abstract Factory. However, I wouldn't be too strict about the naming here. Please see the FAQ section for the differences between these two patterns.

Removing coupling between classes also becomes very handy for unit tests. When we write tests, we often want to reduce external dependencies to ensure that our tests execute deterministically. We can use two factory methods to achieve this: one to construct objects with access to external resources and another for creating test stubs with predefined behavior.

Production code replaced by test stubs via a factory method.
A factory method can be used to replace an object with external dependencies by a test stub.

The production code uses the production factory method (implemented by the ConcreteCreator) for creating "real" objects. For testing, we can switch to our product-stub factory (the StubCreator).

Improving Expressiveness

While infrequent, even a static factory method can make sense. Technically, the constructor of a class is also a (static) factory method, although most languages limit its naming. Having two constructors with the same signature (name and parameters) is often not possible.

But we can define a static factory method to bypass this limitation as for methods, there are much fewer restrictions regarding the name. See, for example, this example (from the German Factory-Method Wikipedia page):

A Color class with two static factory methods.
Factory Methods can help where constructors are too limited.

Our Color class has two static factory methods with the same signature but semantically different arguments. The different methods help make our API more expressive and convenient. Using constructors alone, such an implementation would be impossible.

Implementation

Implementing this pattern in an OOP language comes with relatively little effort: All we have to do is derive a subclass and override its factory method. If the base class contains other implementations, we can leave them untouched.

You may have recognized that the original Factory Method pattern description is quite OOP-centric. This might be for historical reasons - OOP was a very emerging concept at the time this pattern was first described.

Today, most people would agree that using higher-order functions to implement this pattern would be much more convenient.

Many recent frameworks or libraries use this more functional approach: Angular's dpendency injection mechanism, for instance, expects a single factory function as dependency provider instead of a complete implementation class.

// Angular factory method for providing services
const heroServiceFactory = (logger: Logger, userService: UserService) =>
  new HeroService(logger, userService.user.isAuthorized);

export const heroServiceProvider ={ 
    provide: HeroService,
    useFactory: heroServiceFactory,
    deps: [Logger, UserService]
};

The dependency mechanism in the .NET framework is similar. This extension method registers services in the dependency provider. At the last parameter position, the method expects a factory function that returns an object of the service type TService.

// .NET service registration via factory method
public static IServiceCollection AddSingleton<TService> (
    this IServiceCollection services, 
    Func<IServiceProvider,TService> implementationFactory) 
    where TService : class;

FAQ

Factory, Factory Method, Abstract Factory - What's the difference?

Technically, the Abstract Factory is a class consisting of several factory methods, each responsible for creating a specific type of product. In that way, the creation of several related products can be grouped together into one class. The Factory Method's focus, on the other hand, lies more on creating products of a single type.

I like to compare the Abstract Factory with the barracks building in Warcraft (or any similar real-time-strategy game): The building provides different factory methods, one for creating a melee unit, another for creating distance fighters, and so on. Each faction has its own implementation of this building that produces faction-specific representations of these units. The human barracks, for instance, train foot soldiers, while the Orcish one produces Grunts instead.

From a conceptual point of view, the Abstract Factory pattern delegates the construction to a different class. In contrast, the Factory Method is only a single method within a class that may have another purpose otherwise. Which approach to use best might depend on your concrete use case.

The more general term Factory is not linked to any concrete pattern. It is often used to describe the broader concept of delegating the creation logic of an object to another class. This includes both the Abstract Factory and the Factory Method, but also the purely functional approaches we've seen in the Implementation section.

Are there any pitfalls when using a Factory Method?

Using the Factory Method is relatively safe thanks to its easy structure. However, like most patterns, it increases your code's abstraction level. When using factories, object creation is not transparent anymore. Instead, you must read the factory's implementation to determine which concrete type of object it instantiates. This can become even more difficult to track if your classes are resolved through a dependency container.

Also, many factory implementations often return only interfaces instead of concrete types. This means your client code can not access any type-specific methods if they're not part of the interface. If you need access to subtype functionality, you may need additional patterns, like, for example, the Visitor.

References