Implementing Factory Methods
What you'll learn: How to write concrete factory methods that create different object types based on input parameters.
The Core Idea
A factory method is a function that decides which specific class to instantiate based on parameters you pass in. Instead of calling constructors directly throughout your code, you call the factory method—it handles the "how" of object creation for you.
Think of it like ordering at a restaurant. You don't go into the kitchen and assemble your meal—you tell the waiter what you want (the parameter), and the kitchen (the factory method) decides exactly how to prepare it and what to serve you.
How Factory Methods Work
The factory method takes input (often a string, enum, or configuration value) and uses conditional logic to determine which concrete class to create:
function createShape(type):
if type equals "circle":
return new Circle()
else if type equals "square":
return new Square()
else if type equals "triangle":
return new Triangle()
else:
throw error "Unknown shape type"
The caller doesn't need to know about Circle, Square, or Triangle classes—they just ask for a shape by name.
Key Characteristics
- Encapsulates creation logic in one place
- Returns objects through a common interface (all shapes share the same base type)
- Centralizes object creation decisions, making changes easier
- Hides concrete class names from calling code
This pattern supports the Open/Closed Principle: adding new shape types only requires modifying the factory method, not every place that creates shapes.
Key Takeaway: Factory methods use parameters to decide which concrete object to create, centralizing instantiation logic and decoupling client code from specific class names.