How would you implement the Abstract Factory pattern in Java?

The Abstract Factory pattern is implemented by defining a factory interface with a creation method per product type, then writing one concrete factory class per product family that implements those methods to return matching, compatible products.

Key Points: • Start with an abstract factory interface declaring one method per product to create. • Each concrete factory implements the interface and returns products from a single, consistent family. • Client code depends only on the abstract factory and abstract product interfaces, never on concrete classes. • The concrete factory to use is usually chosen once, at startup or via configuration, and reused throughout the application. • New product families are added by creating a new concrete factory, without touching existing client code.

Example: A cross-platform UI library might define a GUIFactory interface with createButton() and createCheckbox() methods, then provide WindowsFactory and MacFactory implementations so the whole application renders a consistent set of native-looking widgets depending on which factory is selected.

Code Example:

interface GUIFactory {
    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(); }
}

Interview Tip: A concise interview answer is:

"I define an abstract factory interface with one creation method per product, then implement a concrete factory class per product family. Client code only ever talks to the abstract factory and abstract product types, so switching or adding a whole family of related products doesn't touch existing code."