CreationalverifiedVerified

Factory Method

Defines an interface for creating an object but lets subclasses decide which class to instantiate. Defers instantiation to subclasses.

Coming Soon

errorWhat Problem Does the Factory Method Pattern Solve?

When code depends on concrete classes to create objects, adding a new type forces changes everywhere instantiation occurs. This scatters creation logic, violates the Open/Closed Principle, and tightly couples client code to specific implementations.

check_circleHow the Factory Method Pattern Works

Declare a factory method in a base class that returns a product interface. Each subclass overrides the factory method to produce a different concrete product. Client code works only with the product interface, so new types can be introduced by adding a new subclass without modifying existing code.

Factory Method Pattern Architecture

hourglass_empty

Rendering diagram...

Implementation by Language

lightbulb

Factory Method Pattern in the Real World

Think of a logistics company that ships packages. The headquarters defines the shipping process but doesn’t decide the vehicle. Regional offices (subclasses) choose whether to use trucks, ships, or drones based on local conditions. The headquarters just says ‘get me a transport’ and the regional office delivers the right one.

Frequently Asked Questions

helpWhat is the difference between Factory Method and Abstract Factory?

Factory Method uses inheritance — a single method in a base class is overridden by subclasses to create different products. Abstract Factory uses composition — an entire factory object is passed in, capable of creating families of related products. Factory Method creates one product; Abstract Factory creates many.

helpWhen should I use Factory Method instead of a simple constructor?

Use Factory Method when the exact class to instantiate is determined at runtime, when creation logic is complex enough to warrant encapsulation, or when you want to decouple client code from concrete implementations. If the class is always known at compile time, a constructor is simpler.