What is the Abstract Factory pattern and how does it differ from Factory Method?

Topic: design-patterns, Creational Patterns. Level: Intermediate.

Answer

Abstract Factory provides an interface to create **families of related objects** without specifying their concrete classes — e.g. a `WindowsFactory` produces a matching `WindowsButton` + `WindowsCheckbox`, a `MacFactory` produces Mac variants. It guarantees the products used together are compatible. Difference: **Factory Method** creates one product via inheritance (a method); **Abstract Factory** creates several related products via composition (an object with multiple create methods). Use Abstract Factory when your system must be independent of how a whole family of products is created. ```java interface Button { void render(); } interface Checkbox { void render(); } interface GUIFactory { // creates a FAMILY of related widgets Button createButton(); Checkbox createCheckbox(); } class WindowsFactory implements GUIFactory { public Button createButton() { return new WindowsButton(); } public Checkbox createCheckbox() { return new WindowsCheckbox(); } } class MacFactory implements GUIFactory { public Button createButton() { return new MacButton(); } public Checkbox createCheckbox() { return new MacCheckbox(); } } // Client gets a consistent family; no mixing Win button with Mac checkbox. GUIFactory f = isWindows ? new WindowsFactory() : new MacFactory(); f.createButton().render(); f.createCheckbox().render(); ```