Creational Design Pattern
Abstract Factory Design Pattern in Java
Create families of related objects without coupling client code to concrete product classes.
In this lesson: Abstract Factory groups multiple Factory Methods behind one factory interface. The client requests related products from the same family without knowing which concrete classes are being used.
Overview
Abstract Factory is useful when products must be compatible with one another. A UI toolkit, database provider, or cloud platform can expose a factory that creates all products for one environment.
Implementation
interface Button { void render(); }
interface Checkbox { void check(); }
interface UiFactory {
Button createButton();
Checkbox createCheckbox();
}
The client can now work with the shared abstractions while the concrete implementations remain behind the pattern boundary.
final class WindowsFactory implements UiFactory {
public Button createButton() { return new WindowsButton(); }
public Checkbox createCheckbox() { return new WindowsCheckbox(); }
}
final class LinuxFactory implements UiFactory {
public Button createButton() { return new LinuxButton(); }
public Checkbox createCheckbox() { return new LinuxCheckbox(); }
}
Example usage
UiFactory factory = new WindowsFactory();
Button button = factory.createButton();
Checkbox checkbox = factory.createCheckbox();
button.render();
checkbox.check();
When should you use it?
Use Abstract Factory when an application must work with several product families and products from one family must remain consistent. It adds interfaces and concrete factory classes, so it can be excessive for a small set of unrelated objects.
Next step: Continue with the Design Patterns course and explore the next pattern category.