What is the difference between Factory Method and Abstract Factory?
Factory Method and Abstract Factory are both creational patterns, but they solve different problems in terms of scale and abstraction.
1. Level of the task
- Factory Method - creates one object of a specific type, chosen by the subclass.
- Abstract Factory - creates a whole family of related objects, ensuring their compatibility with each other.
Example:
- Factory Method can create only a button (WindowsButton or MacButton).
- Abstract Factory creates the whole group of interface elements (a button, a menu, a window) for a specific OS.
2. Structure
- Factory Method is a single method that subclasses override.
- Abstract Factory is an interface or class that contains a set of factory methods, one for each product in the family.
3. Relationship between them
Abstract Factory is often implemented using several Factory Methods internally. In other words, Abstract Factory is a layer on top that combines several factory methods.
4. Example
Factory Method:
java
abstract class Dialog {
abstract Button createButton();
}Abstract Factory:
java
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}5. Summary
| Criterion | Factory Method | Abstract Factory |
|---|---|---|
| Scale | One product | Family of products |
| Implementation | Inheritance and method overriding | Combination of factory methods |
| Flexibility | Creating one type of object | Guaranteed compatibility between several objects |
| Example | createTransport() -> Truck | createGUI() -> Button + Checkbox |
Conclusion: Factory Method answers "which exact object to create", Abstract Factory answers "which compatible objects to create together".
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.