Abstract Factory Design Pattern in Java
A factory that creates a whole family of related objects. All objects from one factory match each other.
Real life example
A furniture shop sells a Modern set or a Classic set. A sofa and a chair from the same set always match.
When to use
You must create groups of objects that belong together, like dark theme and light theme widgets.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
public class Main {
public static void main(String[] args) {
UIFactory f = new DarkFactory(); // change this one line to switch the whole theme
f.createButton().draw(); // Dark button
f.createCheckbox().draw(); // Dark checkbox
}
}
interface Button { void draw(); }
interface Checkbox { void draw(); }
class DarkButton implements Button { public void draw() { System.out.println("Dark button"); } }
class DarkCheckbox implements Checkbox { public void draw() { System.out.println("Dark checkbox"); } }
class LightButton implements Button { public void draw() { System.out.println("Light button"); } }
class LightCheckbox implements Checkbox { public void draw() { System.out.println("Light checkbox"); } }
interface UIFactory { Button createButton(); Checkbox createCheckbox(); }
class DarkFactory implements UIFactory {
public Button createButton() { return new DarkButton(); }
public Checkbox createCheckbox() { return new DarkCheckbox(); }
}
class LightFactory implements UIFactory {
public Button createButton() { return new LightButton(); }
public Checkbox createCheckbox() { return new LightCheckbox(); }
}
Output
Dark button
Dark checkbox