Let's consider a real-world example with a software application that supports multiple operating systems (OS) like Windows and MacOS. Depending on the OS, the application should create appropriate controls like buttons, checkboxes, and menus. Here, we can use the Abstract Factory pattern to create a separate factory for each OS.
Here is an example in Java:
// Abstract product A public interface Button { void render(); } // Abstract product B public interface Checkbox { void render(); } // Concrete product A1 public class WindowsButton implements Button { public void render() { System.out.println("Rendering Windows style button..."); } } // Concrete product B1 public class WindowsCheckbox implements Checkbox { public void render() { System.out.println("Rendering Windows style checkbox..."); } } // Concrete product A2 public class MacOSButton implements Button { public void render() { System.out.println("Rendering MacOS style button..."); } } // Concrete product B2 public class MacOSCheckbox implements Checkbox { public void render() { System.out.println("Rendering MacOS style checkbox..."); } } // Abstract Factory public interface GUIFactory { Button createButton(); Checkbox createCheckbox(); } // Concrete Factory 1 public class WindowsGUIFactory implements GUIFactory { public Button createButton() { return new WindowsButton(); } public Checkbox createCheckbox() { return new WindowsCheckbox(); } } // Concrete Factory 2 public class MacOSGUIFactory implements GUIFactory { public Button createButton() { return new MacOSButton(); } public Checkbox createCheckbox() { return new MacOSCheckbox(); } } // Client code public class Client { private Button button; private Checkbox checkbox; public Client(GUIFactory factory) { button = factory.createButton(); checkbox = factory.createCheckbox(); } public void renderGUI() { button.render(); checkbox.render(); } public static void main(String[] args) { Client windowsClient = new Client(new WindowsGUIFactory()); windowsClient.renderGUI(); // Renders Windows style button and checkbox Client macClient = new Client(new MacOSGUIFactory()); macClient.renderGUI(); // Renders MacOS style button and checkbox } }
In this example, Button
and Checkbox
are the abstract products. WindowsButton
, WindowsCheckbox
, MacOSButton
, and MacOSCheckbox
are the concrete products. GUIFactory
is the abstract factory that declares a set of methods for creating each abstract product. WindowsGUIFactory
and MacOSGUIFactory
are the concrete factories that implement these creation methods to produce the concrete products. The Client
uses only interfaces declared by the abstract factory and abstract product classes. This allows you to create a new factory that creates controls for a different OS without changing the client code.