Factory Method
Define an interface for creating an object, but let subclasses decide which class to instantiate.
A method that makes objects.
The Factory Method pattern gives a class a special method whose job is to create
objects. Instead of calling new ConcreteThing() all over your code, you call
createThing() — and subclasses can override it to make a different concrete thing.
Example: a Dialog base class has a createButton() method.
WindowsDialog overrides it to return a WindowsButton, while
WebDialog returns an HtmlButton. The dialog code stays the same.
# Problem: client hard-codes which concrete class to construct. def notify(channel, msg): if channel == "email": EmailSender().send(msg) elif channel == "sms": SmsSender().send(msg) # new channel => edit this function
# Fix: Factory Method — subclasses decide which product to create. from abc import ABC, abstractmethod class Sender(ABC): @abstractmethod def send(self, msg): ... class Notifier(ABC): @abstractmethod def create_sender(self) -> Sender: """Factory Method: override to pick the product.""" def notify(self, msg): sender = self.create_sender() # creation deferred to subclass sender.send(msg) class EmailNotifier(Notifier): def create_sender(self): return EmailSender() EmailNotifier().notify("hi") # client uses Notifier API only
Decoupling creation from use.
The pattern has a product interface, concrete products, a creator (declaring the factory method), and concrete creators (overriding it). The creator's other code uses products only through the interface, so it never depends on concrete classes — new products arrive by adding a subclass.
Trade-offs and relations.
- OCP & DIP — clients depend on the product abstraction; new variants extend without editing existing code.
- Parallel hierarchies — a downside: each new product may need a matching creator subclass.
- vs Abstract Factory — Factory Method creates one product via inheritance; Abstract Factory creates families via composition.
- Template Method connection — a factory method is often a step called by a template method.
Interview Questions
A creational pattern that defines a method for creating an object but lets subclasses decide which concrete class to instantiate, so the object's creation is deferred to subclasses.
It removes hard-coded new ConcreteClass() calls from client code, decoupling code that uses objects from the code that creates them, so new product types can be introduced without changing the consumer.
Product (interface), ConcreteProduct (implementations), Creator (declares the factory method, may have a default), and ConcreteCreator (overrides the factory method to return a specific product).
Creational — it's about how objects are created.
A logistics app with a Transport product: RoadLogistics creates a Truck, SeaLogistics creates a Ship. The planning code works with Transport and doesn't care which concrete vehicle it got.
No. The client works with the product through its interface/abstract type; the concrete class is chosen inside the factory method, so the client stays decoupled from concrete types.
The base creator declares the factory method but the actual choice of which concrete product to build is made by whichever subclass overrides that method — so the decision is pushed down the inheritance hierarchy.
A "simple factory" is just one method/class that decides which product to build, typically with a conditional/switch — not a GoF pattern. Factory Method uses inheritance: the creation method is abstract/overridable, and subclasses provide the concrete choice via polymorphism. Simple factory centralizes creation but you edit its switch for each new type; Factory Method lets you add a new creator subclass instead, aligning better with the Open/Closed Principle.
Because the creator's code depends only on the product interface and calls the overridable factory method, you can introduce a new product by adding a new ConcreteProduct plus a ConcreteCreator subclass — without modifying the existing creator or client code. Existing, tested code stays closed while the system is open to new products through extension.
Factory Method is frequently used as a step within a Template Method. The base class defines an algorithm (template method) that at some point needs to create an object; it calls the factory method for that, and subclasses supply the concrete product. So the template method controls the overall flow while the factory method is one of the overridable hooks that customizes what gets created.
Because a concrete creator is paired with a concrete product, adding a product often means adding a matching creator subclass, so two hierarchies grow in lockstep. This adds classes and boilerplate and can feel heavy when you only need to vary one object. It's a common criticism: for simple cases a parameterized factory or DI may be lighter than a full inheritance-based Factory Method.
Yes. The Creator can provide a default that returns a sensible default product, so subclasses only override it when they need a different one. This is useful when there's a common/most-frequent product and only some variants require change — it reduces the number of subclasses you must write.
Pass an argument (e.g. a type/key/enum) to the factory method so a single method can create different products based on the parameter, instead of one subclass per product. This is a pragmatic middle ground: fewer classes, but you reintroduce a conditional and must edit it for new types (unless combined with a registry). It's often called a parameterized factory and blurs into the "simple factory" idea.
Many framework "create" hooks: Java's Iterable.iterator() (each collection returns its own Iterator), Collection.iterator(), URLStreamHandler.openConnection(), and numerous framework methods where a base class calls an overridable createX(). Any place a base type declares a method returning a product that subclasses specialize is effectively Factory Method.
Both decouple clients from concrete products, but differ in mechanism and scope. Factory Method uses inheritance: a single overridable method creates one product, and you subclass the creator to vary it. Abstract Factory uses composition: an object exposes multiple creation methods to build a whole family of related products, and you swap the factory object to change the family. Factory Method is finer-grained (one product, via subclassing) and often implemented using factory methods internally by an Abstract Factory. Choose Factory Method when a class can't anticipate the one product type it must create; choose Abstract Factory when you must ensure a set of products are used together consistently and swappable as a unit. They compose: an Abstract Factory's methods are frequently Factory Methods.
Often DI handles "give me an implementation of this interface" more cleanly, so pure Factory Method is less needed for simple substitution. But Factory Method still shines when creation depends on runtime information not known at wiring time (e.g. build a product based on user input, message content, or state), when you need to encapsulate non-trivial construction logic, or when a base class's algorithm must create objects whose type varies by subclass. In DI-heavy code you often inject a factory (or use assisted injection / provider) rather than the product, marrying both ideas: DI supplies the factory, and the factory encapsulates the runtime creation decision. So it's not obsolete; its role shifts toward runtime/parameterized creation and encapsulating construction, while static dependency substitution goes to DI.
Techniques: use a parameterized factory method (one method keyed by type) instead of one creator subclass per product; back it with a registry/map from key to a constructor or supplier (e.g. Map<String, Supplier<Product>>) so new products self-register without editing a switch, preserving OCP without new creator classes; use reflection/DI to instantiate by type; or in languages with first-class functions, pass a creation function instead of subclassing. The trade-off is losing some of the compile-time, inheritance-based structure in exchange for far fewer classes. Pick based on how many products exist and whether the extra type safety of separate creators earns its boilerplate.
The high-level creator code operates entirely against the abstract Product type and an abstract creation method — it never names a concrete product. The concrete decision lives in low-level ConcreteCreator subclasses that implement the abstraction. Thus high-level policy (the algorithm using products) depends on abstractions, and the concrete details (which product) depend on/implement those abstractions — exactly DIP. This is why Factory Method is a building block for pluggable designs: the stable core is written against interfaces and factory hooks, while concrete product choices are provided by extensions, keeping the dependency arrows pointing toward abstractions.
Because clients use products only through the abstract type, every concrete product returned by any factory method must be genuinely substitutable (LSP). If a ConcreteProduct throws on some interface methods, weakens guarantees, or behaves inconsistently, client code written against the interface breaks in ways the factory hid, and bugs surface far from the factory. This couples the reliability of Factory Method to LSP compliance of all products. Mitigation: define a clear product contract, cover it with a shared contract-test suite run against every concrete product, and keep the interface narrow (ISP) so products aren't forced to implement operations they can't support. The pattern's decoupling benefit only holds if the products are truly interchangeable behind the interface.
The pattern actually aids testing: because creation is behind an overridable method, a test can subclass the creator and override the factory method to return a stub/mock product, isolating the algorithm under test from real product construction (e.g. avoid hitting a real network client). Alternatively, if the factory is injected as a collaborator, provide a fake factory. You then verify the creator's logic against the controlled product. You'd also separately test each ConcreteCreator returns the correct product type and each ConcreteProduct against the product contract. The key is that the factory method is a seam you can substitute, which is one of the pattern's testability advantages over hard-coded new.