What is the difference between the Factory Method and Abstract Factory patterns?
Factory Method lets a subclass decide which single product to create. Abstract Factory creates a whole family of related products that are meant to be used together.
Explain it simply
A restaurant franchise: each branch decides how it makes its "dish of the day" (Factory Method). A furniture shop that sells a complete matching set in one style, modern or classic, with chair, table and sofa together, is Abstract Factory.
Factory Method varies one product through inheritance. Abstract Factory varies a group of products so they match each other.
Example
// Factory Method: subclass picks the product
abstract class Dialog {
abstract Button createButton();
void render() { createButton().draw(); }
}
class WindowsDialog extends Dialog { Button createButton() { return new WinButton(); } }
class WebDialog extends Dialog { Button createButton() { return new HtmlButton(); } }
// Abstract Factory: one object creates a matching family
interface UiFactory {
Button createButton();
Checkbox createCheckbox();
}
class DarkFactory implements UiFactory { /* DarkButton, DarkCheckbox */ ... }
class LightFactory implements UiFactory { /* LightButton, LightCheckbox */ ... }
void build(UiFactory f) {
Button b = f.createButton();
Checkbox c = f.createCheckbox(); // guaranteed to match b
}Abstract Factory is often implemented using several factory methods inside one class.
What to say in the interview
"Factory Method is one overridable method that creates a single product, with the choice left to subclasses. Abstract Factory is an interface that creates a family of related objects so they stay consistent, such as dark or light UI sets."
Common mistakes
- Mixing up which one is based on inheritance. Factory Method is; Abstract Factory is based on composition and an object.