Sobes.tech
Junior — Middle

Can you explain the principle of the Abstract Factory pattern and its structure?

sobes.tech AI

Answer from AI

The Abstract Factory pattern is designed to create families of related objects without specifying their concrete classes.

Principle of operation:

  • An interface or abstract class for the factory is defined, which declares methods for creating various products.
  • Concrete factories implement this interface and create specific products belonging to one family.
  • The client works with the factory through the abstract interface and is independent of the concrete classes of the objects being created.

Structure:

  • AbstractFactory — interface with methods for creating products.
  • ConcreteFactory — a specific factory implementing AbstractFactory.
  • AbstractProduct — interface for products.
  • ConcreteProduct — specific products created by the factory.

Example in Java:

interface GUIFactory {
    Button createButton();
    Checkbox createCheckbox();
}

class WinFactory implements GUIFactory {
    public Button createButton() { return new WinButton(); }
    public Checkbox createCheckbox() { return new WinCheckbox(); }
}

class MacFactory implements GUIFactory {
    public Button createButton() { return new MacButton(); }
    public Checkbox createCheckbox() { return new MacCheckbox(); }
}

// Client
class Application {
    private Button button;
    private Checkbox checkbox;

    public Application(GUIFactory factory) {
        button = factory.createButton();
        checkbox = factory.createCheckbox();
    }
}

This approach simplifies the replacement of product families and supports extensibility.