creational

Abstract Factory

Provide an interface for creating families of related objects without specifying their concrete classes.

Sometimes objects only make sense together. A Windows button, a Windows checkbox and a Windows menu belong in one set. Mixing a Windows button with a Mac checkbox would look broken.

If each object is created separately, nothing stops that mix-up. Someone adds one line in the wrong place and the set breaks.

Abstract Factory hands out whole families. You pick the factory once, at startup. After that, every object it gives you is guaranteed to belong to the same family.

What the interviewer is probing.

1. "How does it differ from Factory Method?" *Probing:* the distinction. *Stalls:* "They are the same." *Moves up:* Factory Method creates one product through inheritance; Abstract Factory creates families of related products through composition.

2. "What is the motivating case?" *Probing:* the fit. *Stalls:* "Flexibility." *Moves up:* products that must be used together and must match — a UI toolkit per platform, or a set of database-specific DAOs.

3. "What is the cost?" *Probing:* the trade. *Stalls:* "None." *Moves up:* adding a new product type means changing the abstract factory and every implementation — it is rigid in that direction.

4. "Where would you see it in a framework?" *Probing:* the practical angle. *Stalls:* "Nowhere." *Moves up:* connection and statement creation in JDBC drivers, and document builder factories in XML parsing.

A furniture store sells matched sets — Victorian style gives you all Victorian items; Modern gives you all Modern.

Key Concepts

1
One interface declares a create method for each product in the family: createButton(), createCheckbox(), createMenu().
createButton()createCheckbox()createMenu()
2
Each concrete factory implements all of them for one family. WindowsFactory returns only Windows parts. MacFactory returns only Mac parts.
WindowsFactoryMacFactory
3
Your application holds a reference to the interface, not to a specific factory. It calls createButton() without knowing or caring which family it is working with. Switching the whole look means swapping one object at startup.
createButton()
4
Note the trade-off. Adding a new family is easy: write one more factory. Adding a new product is not: you must change the interface and every factory that implements it.
java
public interface UIFactory {
    Button createButton();
    Checkbox createCheckbox();
}
public class MacFactory implements UIFactory {
    public Button createButton() { return new MacButton(); }
    public Checkbox createCheckbox() { return new MacCheckbox(); }
}
public class WinFactory implements UIFactory {
    public Button createButton() { return new WinButton(); }
    public Checkbox createCheckbox() { return new WinCheckbox(); }
}