Pattern · Advanced

Abstract Factory

Create whole FAMILIES of related objects (a Button + a Checkbox that match) through one factory, guaranteeing the pieces always belong together.

Asked atAmazonMicrosoftAdobe
step 1 / 7
One factory, a whole family
«interface»
GUIFactory
+ makeButton()
+ makeCheckbox()
WinFactory
MacFactory
«interface»
Button
«interface»
Checkbox
One factory, a whole family
1interface GUIFactory {
2 Button makeButton(); // one method per product
3 Checkbox makeCheckbox(); // in the family
4}
5class WinFactory implements GUIFactory { ... } // all-Windows
6class MacFactory implements GUIFactory { ... } // all-Mac
7 
8GUIFactory f = onMac ? new MacFactory() : new WinFactory();
9Button b = f.makeButton();
10Checkbox k = f.makeCheckbox(); // guaranteed to match b
State
factoryone method per product

GUIFactory declares makeButton() and makeCheckbox() — one create-method per product in the family.