Creational PatternsFactory Method PatternMedium⏱️ ~2 min

Factory Method Pattern Structure

Participants and Their Roles:

The Factory Method Pattern involves four key participants. First, the Product interface defines the interface of objects the factory method creates. Second, ConcreteProduct classes implement the Product interface. Third, the Creator declares the factory method that returns a Product object. Fourth, ConcreteCreator classes override the factory method to return specific ConcreteProduct instances.

«interface»
Product
+ operation(): void
ConcreteProductA
+ operation(): void
ConcreteProductB
+ operation(): void
▲ implements
Creator
+ factoryMethod(): Product
+ someOperation(): void
ConcreteCreatorA
+ factoryMethod(): Product
ConcreteCreatorB
+ factoryMethod(): Product
Key Relationships:

First, ConcreteProduct classes implement the Product interface (▲ inheritance/implementation). Second, ConcreteCreator classes extend the Creator class (▲ inheritance). Third, Creator depends on the Product interface but not on concrete products. Fourth, each ConcreteCreator creates a specific ConcreteProduct.

Method Responsibilities:

The factoryMethod() is abstract or returns a default Product. The someOperation() in Creator uses the product returned by factoryMethod() but does not know the concrete type. ConcreteCreators override factoryMethod() to return specific ConcreteProduct instances.

Interview Tip: Emphasize that the Creator class can contain business logic that uses the product but does not create it directly. This separates usage from creation.
💡 Key Takeaways
Creator class declares abstract factoryMethod() that returns Product interface
ConcreteCreator subclasses override factoryMethod() to return specific products
Products implement a common interface ensuring interchangeability
Creator's business logic depends on Product interface, not concrete classes
📌 Examples
1Creator.someOperation() might call product.operation() without knowing if it is ProductA or ProductB
← Back to Factory Method Pattern Overview