How does Abstract Factory differ from Factory Method?
Abstract Factory and Factory Method solve similar problems, encapsulating object creation, but at different levels of abstraction.
1. The scale of the task
- Factory Method creates one object (one product type).
- Abstract Factory creates a family of related objects (several types that must work together).
Example:
Factory Method creates a single button (Button).
Abstract Factory creates a whole set of interface elements - a button, a checkbox, and a window - compatible with each other (for example, all in macOS style).
2. Implementation
- Factory Method is implemented through inheritance: subclasses override the factory method.
- Abstract Factory uses composition: it contains a set of factory methods for different products.
java
// Factory Method
abstract class Dialog {
abstract Button createButton();
}
// Abstract Factory
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}3. The relationship between them
Abstract Factory is often built on top of several Factory Methods. Each method inside Abstract Factory can be a factory method for a separate product type.
4. When to apply
- Factory Method: when you need to let subclasses choose which object to create.
- Abstract Factory: when you need to create whole sets of related objects without depending on concrete implementations.
5. The key difference
| Criterion | Factory Method | Abstract Factory |
|---|---|---|
| Scale | One product | Family of products |
| Mechanism | Inheritance | Composition |
| Extension | Adding new types through subclasses | Adding new product families |
| Example | Creating a button | Creating a GUI kit |
Summary: Factory Method answers the question "which exact object to create?", Abstract Factory answers "which related objects to create together?".
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.