Creational Patternscritical

Factory Method Pattern

Define an interface for creating an object but let subclasses decide which class to instantiate. Factory Method defers instantiation to subclasses.

Memory anchor

Factory Method = a pizza shop franchise. The base recipe says 'make dough' but each city's branch (subclass) decides whether it's New York thin crust or Chicago deep dish. The menu (interface) stays the same.

Expected depth

Factory Method is a template method applied to object creation. The creator defines a createProduct() method (the factory method); concrete creators override it. Callers use the creator through the abstract interface, never knowing what concrete product they receive. This enforces DIP: the creator depends only on the Product interface. Common use cases: parsing frameworks (createParser returns XMLParser or JSONParser based on format), UI frameworks (createButton returns WinButton or MacButton), logistics (createTransport returns Truck or Ship).

Deep — senior internals

Factory Method is most useful when the creating class doesn't know ahead of time what class it needs to instantiate, or when subclasses need the ability to vary what they create. It differs from Simple Factory (a static method that switches on type — not a GoF pattern) and from Abstract Factory (a family of related factories). Factory Method is a single-level deferral; Abstract Factory is a family-level deferral. Factory Method typically yields a parallel hierarchy: one for creators, one for products. This can explode combinatorially. A modern alternative is to use a registry — a map from a key to a factory lambda — which achieves OCP without subclassing.

🎤Interview-ready answer

Factory Method separates the question of 'what to create' from 'how to use it'. My DocumentParser base class defines a createParser() method. XMLDocumentParser overrides it to return an XMLParser. The client calls parser.parse() without ever knowing which implementation it has. This satisfies DIP — the client depends only on the Parser interface — and OCP — adding YAML support means adding YAMLParser and YAMLDocumentParser without touching the base. For interview purposes: Factory Method = one product type, deferred to subclass; Abstract Factory = multiple related product types, deferred to a factory family.

Common trap

Factory Method is not just a static method that creates objects — that is a Simple Factory, which is not a GoF pattern. Factory Method is a virtual method overridden by a subclass. If there is no subclass deferral, it is not Factory Method.

Related concepts