What is the Factory Method pattern?
Factory Method is a creational design pattern that defines an interface for creating objects, but lets subclasses decide which class to instantiate. In other words, it delegates object creation to child classes, freeing the main code from being tied to specific types.
Why it is needed
Without a factory method, code often creates objects directly with new, which makes the system rigid and hard to extend.
Factory Method separates the creation logic from the usage logic, which lets you add new product types without changing the client code.
Structure
- Product - a common interface for all created objects.
- ConcreteProduct - specific implementations of the product.
- Creator - declares the factory method that returns a
Productobject. - ConcreteCreator - overrides the factory method, creating the needed product type.
Example (Java)
// Product
interface Transport {
void deliver();
}
// Concrete products
class Truck implements Transport {
public void deliver() {
System.out.println("Delivery by land");
}
}
class Ship implements Transport {
public void deliver() {
System.out.println("Delivery by sea");
}
}
// Creator
abstract class Logistics {
abstract Transport createTransport();
public void planDelivery() {
Transport t = createTransport();
t.deliver();
}
}
// Concrete creators
class RoadLogistics extends Logistics {
Transport createTransport() { return new Truck(); }
}
class SeaLogistics extends Logistics {
Transport createTransport() { return new Ship(); }
}Advantages
- Frees the code from a hard dependency on specific classes.
- Simplifies extension: you can add new product types without changing the client code.
- Improves testability and flexibility.
Disadvantages
- Increases the number of classes in the project.
- Requires inheritance, which is not always convenient.
Summary: Factory Method is a way to move object creation from client code into subclasses, preserving the flexibility and extensibility of the architecture.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.