SOLID & Design Patterns Interview Question #51

What is the Abstract Factory Pattern?

Advanced Patterns, CQRS & Domain-Driven Design Fundamentals Mid-Level Intermediate

Quick Interview Answer

The Abstract Factory Pattern provides an interface for creating families of related or compatible objects without requiring client code to know their concrete classes. It is useful when several products must vary together.

Detailed Explanation

The Abstract Factory Pattern provides an interface for creating families of related or compatible objects without requiring client code to know their concrete classes. It is useful when several products must vary together.

For example, an application may support multiple UI themes where each theme supplies a matching button, dialog, and menu. The client depends on the factory and product abstractions rather than concrete theme classes.

Code Example

public interface IUiFactory
{
    IButton CreateButton();
    IDialog CreateDialog();
}

public class WebUiFactory : IUiFactory
{
    public IButton CreateButton() => new WebButton();
    public IDialog CreateDialog() => new WebDialog();
}