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.
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.
When to use it
- Cross-platform UI toolkits
- Multiple database backends
- Theme systems where all components must match
Watch out for
- Adding a new PRODUCT to the family forces a change to the factory interface and every concrete factory — the pattern makes new families cheap and new products expensive
- Easy to over-apply: if you only ever have one family, the abstraction is pure overhead
- Concrete factory selection has to happen somewhere, and that decision often ends up as the very if/else the pattern was meant to remove
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(); }
}