What is the Factory Method pattern, and how does it differ from calling a constructor directly?
answer
- Method makes the object, not the caller's `new`
- Return type is an abstraction (interface/superclass)
- Caller asks by intent, factory picks the concrete class
- Two senses: GoF (overridable creator) vs static factory
- Constructor: same name, exact class, must allocate
basics
~20 sFactory Method means asking a method to make an object instead of using new yourself. The method decides which concrete class to build and returns it, usually typed as an interface or parent class, so the caller doesn't depend on the exact type.
solid answer
~50 sFactory Method is a creational pattern where object creation is delegated to a method rather than performed by the caller via `new`. The method's return type is an abstraction (interface or superclass), but it internally chooses and instantiates a concrete implementation. This decouples the calling code from concrete classes: the caller programs against the type, and the factory is free to pick the right subtype, reuse cached instances, or change implementations without touching callers. The classic GoF form puts the factory method on a creator class that subclasses override to vary the product. In everyday Java, the term also covers static factory methods like `List.of(...)` or `Calendar.getInstance()`. The key difference from a constructor: a constructor must return a new instance of exactly its own class and has a fixed name, whereas a factory method has a descriptive name, can return any subtype, and can decide whether to create a new object at all.
go deeper
Can say the factory method creates the object instead of the caller using new, and returns an interface type so the caller doesn't depend on the concrete class.
Distinguishes a constructor from a factory method (name, subtype return, no forced allocation) and names a couple of JDK examples like List.of or Calendar.getInstance.
Separates the GoF Factory Method (overridable creator method, deferred instantiation via subclassing) from the everyday static-factory usage, and ties it to Dependency Inversion / decoupling callers from concrete types.
Frames factory methods as the creation-site enforcement of abstraction boundaries across a codebase, weighs them against DI containers and reflection-based instantiation, and discusses API-evolution benefits (changing the concrete type without breaking callers, instance control for caching/flyweight).
## The problem it solves When you write `new ArrayList<>()`, your code is *hard-wired* to the exact class `ArrayList`. The word **coupling** means a dependency between two pieces of code: here the caller is coupled to a concrete class. Coupling to concrete classes is brittle — if you later want a different implementation, you must edit every place that said `new ArrayList<>()`. The **Factory Method pattern** removes that coupling by moving the `new` behind a method. Instead of constructing the object yourself, you call a method that constructs it for you and hands it back. Because the method's declared **return type** is an *abstraction* (an `interface` or a parent `class` — a type that says *what* the object does, not *which* concrete class it is), the caller never learns the concrete class. That concrete class can change freely. ## Constructor vs factory method A **constructor** is the special block invoked by `new ClassName(...)`. It has hard rules: its name must equal the class name, and `new` always returns a brand-new instance of *that exact class*. A **factory method** is just a normal method that returns an object. Compared to a constructor it gains three powers: 1. **A meaningful name.** `BigInteger.probablePrime(...)` reads better than a bare constructor and lets two factories with the same parameter types coexist (constructors can't — they'd have identical signatures). 2. **It can return a subtype.** The declared return type might be `List`, but the actual object could be an `ArrayList`, an immutable list, or an empty-list singleton. The caller doesn't know or care. 3. **It need not create a new object.** It may return a cached or shared instance (e.g. `Boolean.valueOf(true)` always returns the same `Boolean`). A constructor *must* allocate. ## The GoF "Factory Method" vs the everyday Java usage There are two senses of the term and interviews probe both: - **GoF Factory Method (the design pattern):** a *creator* class declares an abstract or overridable method like `createProduct()` that returns a *product* type; concrete subclasses of the creator override it to decide which concrete product to build. The creator's other methods call `createProduct()` without knowing the concrete product. This is *deferred instantiation*: the superclass defines the algorithm, the subclass chooses the object. The variation point is **inheritance** — you subclass the creator. - **Static factory method (Effective Java sense):** a `static` method on a class that returns an instance of that class (or a related type), e.g. `Integer.valueOf(int)`, `List.of(...)`, `Calendar.getInstance()`. There is no creator hierarchy; the method is simply a named, smarter alternative to a public constructor. Most Java code that people loosely call "factory method" is this static-factory form. Both share the core idea: **the caller asks for an object by intent, not by class name**, and the production code decides the concrete type. ## A minimal example ```java interface Notifier { void send(String msg); } class EmailNotifier implements Notifier { public void send(String msg) { /* ... */ } } class NotifierFactory { // factory method: returns the abstraction, hides the concrete class static Notifier create(String channel) { return switch (channel) { case "email" -> new EmailNotifier(); default -> throw new IllegalArgumentException(channel); }; } } // caller is coupled only to Notifier, never to EmailNotifier: Notifier n = NotifierFactory.create("email"); ``` The caller depends on `Notifier` only. Swapping in an `SmsNotifier` is a one-line change inside the factory; no caller changes. ## Why it matters It is the concrete realization of the **Dependency Inversion Principle** (depend on abstractions, not concretions) at the point of object creation, and it underpins much of the JDK and frameworks like Spring, where you rarely call `new` on the things you consume.
- Give three things a static factory method can do that a constructor cannot.Have a descriptive name (and so allow multiple factories with the same parameter types), return a subtype of the declared return type, and return an existing/cached instance instead of always creating a new one (instance control).
- Is `Integer.valueOf(int)` a factory method?Yes — it is a static factory method. It also exercises instance control: for small values (-128..127) it returns a cached, shared Integer rather than a new one.
saying these in an interview costs you the question
- Saying Factory Method and Abstract Factory are the same thing — Abstract Factory creates families of related objects via an object you hold; Factory Method creates one product, classically via subclass override.
- Claiming a constructor can return a subtype — it cannot; only a method can.
- Thinking the pattern requires the caller to know the concrete class — the whole point is that it doesn't.
- Conflating 'static factory method' with the literal GoF pattern without acknowledging both senses exist.