Explore Topics
- 1ClientLogistics shop = new RoadLogistics();Client chooses WHICH concrete creator to install.
- 2Clientshop.planDelivery("Chicago", 800);Calls the workflow on the abstract Logistics type.
- 3LogisticsTransport t = createTransport();Template method calls the factory method β polymorphic dispatch fires here.
- 4RoadLogistics β overrides factoryMethod()return new Truck();RoadLogistics.createTransport() override returns a Truck.
- 5Logisticst.deliver("Chicago", 800);Back in the template method; uses the Product through its abstract type.
- 6Truck β concrete productreturn "Truck rumbled 800 km by road to Chicago";Truck.deliver() β the concrete product's actual behavior.
Add a new mode = add one Logistics subclass + one Transport class.
Factory Method is a creational pattern that hands the responsibility of creating products to a polymorphic operation in a Creator class. Instead of calling `new ConcreteProduct()` directly, client code calls `creator.factoryMethod()` β and the concrete Creator subclass at runtime decides which product to return. This is often summarized as a "virtual constructor" because the choice of which class to instantiate is deferred to subclasses, just like the choice of which override to call is deferred at runtime for any virtual method. Erich Gamma's broader maxim "the `new` operator considered harmful" applies here: hard-coded `new` calls couple client code to concrete classes, and Factory Method is the cheapest way to undo that coupling within a single product family.
- Replace direct `new ConcreteProduct()` calls with a polymorphic factoryMethod() call.
- "Virtual constructor" β defer the choice of concrete product to a subclass override.
- Client code depends only on the abstract Product type, never on concrete products.
- Adding a new product = adding a new Creator+Product pair, NOT editing the client.
- The Creator itself is the extension point β anyone can subclass it to plug in a new product.
- β¦Decouples client code from concrete product classes
- β¦Encapsulates the construction decision in one place per Creator subclass
- β¦Embodies Open/Closed Principle β extend by subclassing, no client edits
- β¦Each Creator subclass has single responsibility for its product line
- β³Requires inheritance β every product family means a new Creator subclass
- β³Subclass proliferation: trivial product variations multiply class count
- β³Indirection: readers must trace the polymorphic dispatch to know what gets built
- β³Overkill when the product set is small and unlikely to grow