creational

Factory Method

Define an interface for creating an object, but let subclasses decide which class to instantiate.

Your code needs to create an object, but you do not want it tied to one specific class.

The moment you write new PdfReport(), that line only works for PDFs. Supporting Excel means going back and adding an if. Do this in ten places and every new format means ten edits to code that was already tested and working.

Factory Method moves the choice into one overridable method. The main logic calls that method and works with whatever comes back. To add a format, you write a new subclass instead of editing the old flow.

What the interviewer is probing.

1. "What problem does Factory Method solve?" *Probing:* the purpose. *Stalls:* "Creating objects." *Moves up:* letting a class defer which concrete type to instantiate to its subclasses, so the base algorithm stays independent of the product.

2. "How does it differ from a simple static factory?" *Probing:* the precision. *Stalls:* "Nothing." *Moves up:* a static factory is a convenience method; Factory Method is a polymorphic hook subclasses override.

3. "When is it over-engineering?" *Probing:* judgement. *Stalls:* "Never." *Moves up:* when there is one implementation and no prospect of another — a constructor is clearer than a hierarchy.

4. "What is the usual real-world trigger?" *Probing:* the practical angle. *Stalls:* "Nothing." *Moves up:* a second implementation appearing, which is the point at which the conditional creation code should become polymorphic.

A logistics company has a createTransport() method. Road logistics returns a Truck; Sea logistics returns a Ship.

Key Concepts

1
A base class declares a method whose job is to create the object, such as createReport(). It may be abstract, or it may return a sensible default.
createReport()
2
The rest of the base class calls that method whenever it needs the object. Importantly, it only uses the interface. It never knows which concrete class it received.
3
Each subclass overrides the method and returns a different type. PdfReportCreator returns a PdfReport, ExcelReportCreator returns an ExcelReport. The shared logic above them does not change.
PdfReportCreatorPdfReportExcelReportCreatorExcelReport
java
public abstract class LogisticsApp {
    public abstract Transport createTransport();
    public void planDelivery() {
        Transport t = createTransport();
        t.deliver();
    }
}
public class RoadLogistics extends LogisticsApp {
    public Transport createTransport() { return new Truck(); }
}
public class SeaLogistics extends LogisticsApp {
    public Transport createTransport() { return new Ship(); }
}