AAbstract Factory
/
GoF · Creational · C# / .NET 10

Families of objects, built without naming their classes

Abstract Factory lets a client assemble a whole family of related objects — a UI kit, a database provider set, a document export pipeline — through one interface, so the family can be swapped as a unit. The trade-off: every new product in the family means touching every factory you've ever written.

17 sections 16 diagrams 21 code samples ~34 min read
WindowsFactory MacFactory same family
Scroll to read
1

TL;DR — Intent and the Core Trade-off

Abstract Factory gives a client one interface for creating an entire family of related objects, so the client never names a concrete class and never has to know which family it's actually assembling with. Swap the factory implementation and every product it hands out changes together, consistently, with zero edits at the call site.

The single rule that defines the pattern: a client depends on one factory interface and a set of product interfaces, and constructs nothing with new beyond that factory itself. If a client is calling new WindowsButton() anywhere alongside an IGuiFactory, the pattern has already leaked.

You buy consistency across a product family and a single seam for swapping the whole family at once. You pay with an interface that grows every time you add a new product — one method added to IGuiFactory becomes an override in every concrete factory you've ever written, whether or not that factory cares about the new product.

That cost isn't hypothetical. It's the whole reason a strong current of criticism (§12) argues that in a codebase already using a DI container, Abstract Factory is frequently the wrong tool — keyed services and composition root wiring solve the "give me the right family" problem without the interface-explosion cost. Hold both truths at once: the pattern is real, well-defined, and occasionally exactly right; it is also frequently reached for out of habit when a simpler mechanism would do.

2

Origins, Classification, and the Problem It Solves

Abstract Factory is a Creational, object-scope pattern in the 1994 Gang of Four catalogue — object-scope because the family relationships are wired up between object instances at runtime, not baked into a class hierarchy at compile time the way Factory Method's class-scope variant is. It first appeared under the name "Kit" in earlier Smalltalk literature; GoF renamed it and generalized it for statically-typed C++ codebases where swapping an entire windowing toolkit (Motif vs. Presentation Manager, in the book's own example) at link time was a genuine, everyday problem.

The pain it was reacting to: a UI toolkit era where "portable across platforms" meant scattering #ifdef blocks — or their C# equivalent, giant switch statements on an enum — through every place a widget got created. Here's that mess, recognizably:

C#
// UiKit/DialogRenderer.cs — before: switch-per-platform, repeated everywhere a widget is built
public sealed class DialogRenderer
{
    private readonly UiTheme _theme; // enum: Windows, MacOs, Linux

    public DialogRenderer(UiTheme theme) => _theme = theme;

    public void RenderConfirmDialog(string message)
    {
        // Every widget site repeats this switch. Add a Linux GTK theme next
        // sprint and you must find and edit every one of them correctly.
        Button okButton = _theme switch
        {
            UiTheme.Windows => new WindowsButton("OK"),
            UiTheme.MacOs   => new MacButton("OK"),
            _ => throw new NotSupportedException($"Unhandled theme {_theme}")
        };

        Checkbox rememberChoice = _theme switch
        {
            UiTheme.Windows => new WindowsCheckbox("Remember my choice"),
            UiTheme.MacOs   => new MacCheckbox("Remember my choice"),
            _ => throw new NotSupportedException($"Unhandled theme {_theme}")
        };

        // Nothing stops a Windows button from pairing with a Mac checkbox if
        // someone forgets to update one switch after adding a theme — the
        // "family" is only a convention living in the programmer's head.
        okButton.Draw();
        rememberChoice.Draw();
    }
}

Two failures compound here: the switch recompiles and grows at every call site whenever a new platform is added, and nothing enforces that the button and checkbox actually come from the same family — a copy-paste slip silently mixes a Windows control with a Mac one, and it compiles fine.

3

Structure and Participants

Canonical structure — two product families, two concrete factories
classDiagram class AbstractFactory { <<interface>> +CreateButton() Button +CreateCheckbox() Checkbox } class WindowsFactory { +CreateButton() Button +CreateCheckbox() Checkbox } class MacFactory { +CreateButton() Button +CreateCheckbox() Checkbox } class Button { <<interface>> +Draw() } class Checkbox { <<interface>> +Draw() } class WindowsButton class MacButton class WindowsCheckbox class MacCheckbox class Client { -factory AbstractFactory +Render() } AbstractFactory <|.. WindowsFactory AbstractFactory <|.. MacFactory Button <|.. WindowsButton Button <|.. MacButton Checkbox <|.. WindowsCheckbox Checkbox <|.. MacCheckbox WindowsFactory ..> WindowsButton : creates WindowsFactory ..> WindowsCheckbox : creates MacFactory ..> MacButton : creates MacFactory ..> MacCheckbox : creates Client --> AbstractFactory Client --> Button Client --> Checkbox
ParticipantRoleBelongs in itMust never be in it
AbstractFactoryDeclares one creation method per product in the familyOnly creation signaturesBusiness logic, shared state
ConcreteFactoryProduces one consistent family (one per variant)Wiring to concrete product constructorsLogic unrelated to construction
AbstractProductDeclares the operations a product family member supportsThe product's public contractAny reference back to its factory
ConcreteProductOne variant's implementation of a productVariant-specific behaviourKnowledge of sibling products' concrete types
ClientConsumes only the abstract factory and abstract productsCalls to factory methods, product operationsAny new WindowsButton()-style construction

The membership test: does this class produce (or get produced as) one coherent, interchangeable-as-a-set variant? If a class varies independently of the rest of the family — a logging strategy that's identical regardless of which UI theme is active — it isn't a family member, no matter how tempting it is to add a CreateLogger() method to the factory just because the factory is already there.

4

The Central Mechanic

The trick is narrower than it looks: the client depends on exactly one factory reference, obtained once, and every product it subsequently touches is a downstream consequence of that single choice. There's no double dispatch here and no wrapper trick — the mechanic is closure over a choice. Pick MacFactory once, and every button, checkbox, and dialog produced from it is guaranteed consistent, because they all trace back to the one object.

One factory reference, many consistent products
flowchart LR A["Client holds one\nIGuiFactory reference"] --> B["CreateButton()"] A --> C["CreateCheckbox()"] A --> D["CreateScrollbar()"] B --> E["Always the Windows variant\nor always the Mac variant\n— never mixed"] C --> E D --> E classDef pick fill:transparent,stroke:#6D28D9,stroke-width:1.5px; class A pick

Compare that to calling four separate static factory methods with a theme parameter passed to each — nothing there prevents the parameter from drifting between calls. Here, the family choice is made exactly once, and the type system enforces the rest.

Step through — client resolves a family and builds a dialog
ClientDialogRenderer MacFactoryConcreteFactory MacButtonConcreteProduct MacCheckboxConcreteProduct

5

Implementation in C# — Naive, Then Idiomatic

Pass one — the textbook translation

C#
// UiKit/IGuiFactory.cs — naive, literal GoF translation
namespace UiKit
{
    public interface IGuiFactory
    {
        IButton CreateButton();
        ICheckbox CreateCheckbox();
    }

    public interface IButton { void Draw(); }
    public interface ICheckbox { void Draw(); }

    public class WindowsFactory : IGuiFactory
    {
        public IButton CreateButton() { return new WindowsButton(); }
        public ICheckbox CreateCheckbox() { return new WindowsCheckbox(); }
    }

    public class WindowsButton : IButton
    {
        public void Draw() { Console.WriteLine("Rendering a Windows-styled button"); }
    }

    public class WindowsCheckbox : ICheckbox
    {
        public void Draw() { Console.WriteLine("Rendering a Windows-styled checkbox"); }
    }
}

This works and is honest, but it's 2026-flavourless: no nullable annotations, mutable-by-default classes, no primary constructors, and manual new-ing of the factory somewhere the client lives.

Pass two — the version an experienced .NET developer writes in 2026

C#
// UiKit/IGuiFactory.cs — idiomatic C# 14 / .NET 10
namespace UiKit;

public interface IGuiFactory
{
    IButton CreateButton();
    ICheckbox CreateCheckbox();
}

public interface IButton { void Draw(); }
public interface ICheckbox { void Draw(); }

// sealed by default: this factory has no reason to be extended via inheritance
public sealed class WindowsFactory : IGuiFactory
{
    public IButton CreateButton() => new WindowsButton();
    public ICheckbox CreateCheckbox() => new WindowsCheckbox();
}

// a record for a stateless product: value-equality is free and correct here
public sealed record WindowsButton : IButton
{
    public void Draw() => Console.WriteLine("Rendering a Windows-styled button");
}

public sealed record WindowsCheckbox : ICheckbox
{
    public void Draw() => Console.WriteLine("Rendering a Windows-styled checkbox");
}

// composition root — the ONLY place that ever chooses a concrete factory
public static class UiKitRegistration
{
    public static IServiceCollection AddUiKit(this IServiceCollection services, UiTheme theme)
    {
        services.AddSingleton<IGuiFactory>(theme switch
        {
            UiTheme.Windows => new WindowsFactory(),
            UiTheme.MacOs   => new MacFactory(),
            _ => throw new NotSupportedException($"Unhandled theme {theme}")
        });
        return services;
    }
}

Three divergences worth calling out specifically. Sealed by default: concrete factories and products are leaf types; nobody should be subclassing WindowsButton, and sealing documents that intent and lets the JIT devirtualize. Records for stateless products: a product with no mutable state is a natural record — value equality is a useful, free side-effect for anything you'll compare in tests. The switch lives in exactly one place — the composition root — rather than a Simple-Factory static method scattered wherever a factory is first needed; this is the one switch the pattern is supposed to eliminate everywhere except here.

6

Variations and Modern .NET Idioms

The classic form — one interface, N concrete factory classes, manual composition-root switch — is not the only shape this takes in current .NET, and for many codebases it's no longer the best default.

VariationHow it worksWhen it's the better fit
Classic concrete-factory classesOne class per family, each implementing the shared factory interfaceFamily count is small and stable; factories carry real construction logic beyond a constructor call
Func<T>-based product delegatesThe "factory" is a small object holding several Func<IButton>-style delegates instead of a named interfaceFamily membership is genuinely just "which constructor to call" with no extra behaviour
Keyed DI services (.NET 8+)IServiceProvider.GetRequiredKeyedService<T>(key) resolves a specific implementation per product, per family keyThe container already owns the object graph; adding a bespoke factory interface duplicates what the container does natively

The honest observation: keyed services have absorbed a large share of what Abstract Factory used to be reached for. When "the family" is just "which registered implementation to hand back," the container already knows how to do that without an extra interface layer — see §7 and §12 for the concrete comparison and the disagreement it produces.

C#
// UiKit/KeyedRegistration.cs — the family expressed as keyed services instead
services.AddKeyedSingleton<IButton, WindowsButton>(UiTheme.Windows);
services.AddKeyedSingleton<IButton, MacButton>(UiTheme.MacOs);
services.AddKeyedSingleton<ICheckbox, WindowsCheckbox>(UiTheme.Windows);
services.AddKeyedSingleton<ICheckbox, MacCheckbox>(UiTheme.MacOs);

// consumer resolves the family member it needs, keyed by the active theme
public sealed class DialogRenderer(
    [FromKeyedServices(typeof(UiTheme))] IButton button,
    [FromKeyedServices(typeof(UiTheme))] ICheckbox checkbox)
{
    public void Render() { button.Draw(); checkbox.Draw(); }
}

Notice what's lost as well as gained: there is no single object embodying "the Mac family" anymore — consistency has to be enforced by registering every keyed pair correctly, rather than by construction. For two products that's a wash; for a family of eight it's a real risk the classic form doesn't have.

7

Where .NET Itself Uses It

ILoggerFactory is the cleanest real-world instance: ILoggerFactory.CreateLogger(string categoryName) hands back an ILogger whose concrete behaviour — console, file, Application Insights, or all three — is entirely determined by how the factory itself was configured at startup, never by the calling code.

C#
// Direct use of the real BCL factory type
using var loggerFactory = LoggerFactory.Create(builder =>
{
    builder.AddConsole();
    builder.AddDebug();
});

ILogger logger = loggerFactory.CreateLogger("Ordering.PricingService");
logger.LogInformation("Quote {QuoteId} priced at {Total:C}", quoteId, total);

The mapping: ILoggerFactory is the AbstractFactory, the console/debug/App-Insights provider configuration is the concrete factory's "family," and every ILogger handed out shares that family's sinks and formatting without the caller ever choosing a provider. System.Data.Common.DbProviderFactory is the older, more literal example — DbProviderFactory.CreateConnection(), CreateCommand(), and CreateParameter() together produce a fully consistent ADO.NET object family for one database engine, selected once by provider name.

Worth flagging as the controversial relative rather than a clean example: IServiceProvider.GetService(Type) resolution is structurally a Service Locator, not Abstract Factory — the client asks a general-purpose container for "give me one of these" rather than depending on a narrow, purpose-built factory interface. The difference matters because Service Locator hides a class's real dependencies from its constructor signature, which is exactly the dependency an Abstract Factory is supposed to make explicit.

8

Runtime Flows

Happy path — resolving and using a consistent family
sequenceDiagram participant C as Client participant DI as Composition Root participant F as MacFactory participant B as MacButton C->>DI: resolve IGuiFactory DI-->>C: MacFactory instance C->>F: CreateButton() F-->>C: MacButton C->>B: Draw() B-->>C: rendered
Failure path — an unregistered family variant
sequenceDiagram participant C as Client participant DI as Composition Root C->>DI: resolve IGuiFactory for LinuxGtk DI-->>C: throws NotSupportedException Note over C: caller must decide -- fall back to a default family or fail startup
Structurally interesting — adding a product mid-family requires touching every factory
sequenceDiagram participant Dev as Developer participant IF as IGuiFactory participant WF as WindowsFactory participant MF as MacFactory Dev->>IF: add CreateScrollbar() Note right of IF: interface now has 3 members IF-->>WF: must implement CreateScrollbar() IF-->>MF: must implement CreateScrollbar() Note over WF,MF: every existing concrete factory now fails to compile until updated
9

Real-World Worked Examples — Three

1. Payments — regional payment-provider families

A checkout service must charge, refund, and tokenize cards through one of several regional payment providers, and every operation for a given transaction must go through the same provider.

C#
// Payments/IPaymentProviderFactory.cs
public interface IPaymentProviderFactory
{
    IChargeGateway CreateChargeGateway();
    ITokenVault CreateTokenVault();
}

public sealed class StripeProviderFactory : IPaymentProviderFactory
{
    public IChargeGateway CreateChargeGateway() => new StripeChargeGateway();
    public ITokenVault CreateTokenVault() => new StripeTokenVault();
}

public sealed class AdyenProviderFactory : IPaymentProviderFactory
{
    public IChargeGateway CreateChargeGateway() => new AdyenChargeGateway();
    public ITokenVault CreateTokenVault() => new AdyenTokenVault();
}

public sealed class CheckoutService(IPaymentProviderFactory providerFactory)
{
    public async Task<ChargeResult> ChargeAsync(Order order, CancellationToken ct)
    {
        var gateway = providerFactory.CreateChargeGateway();
        var vault = providerFactory.CreateTokenVault();
        var token = await vault.TokenizeAsync(order.Card, ct);
        return await gateway.ChargeAsync(token, order.Total, ct);
    }
}
Checkout resolves one provider family for the whole transaction
flowchart LR A[CheckoutService] --> B[IPaymentProviderFactory] B --> C[StripeChargeGateway] B --> D[StripeTokenVault] C --> E[Charge] D --> E

2. Notifications — channel-family bundles (a slightly uncomfortable fit)

A notification service sends both a transactional message and an audit-log entry through one channel — email+inbox-copy, or SMS+delivery-receipt — and the two must be created consistently.

C#
// Notifications/IChannelFactory.cs
public interface IChannelFactory
{
    IMessageSender CreateSender();
    IDeliveryReceipt CreateReceiptWriter();
}

public sealed class EmailChannelFactory : IChannelFactory
{
    public IMessageSender CreateSender() => new SmtpMessageSender();
    public IDeliveryReceipt CreateReceiptWriter() => new InboxCopyWriter();
}

Where this is honestly a stretch: the sender and receipt-writer here don't vary together in any deep sense — an SMS sender and an inbox-copy writer could be paired perfectly well; there is no real coupling forcing the family. A single NotificationChannel record holding two independently-injected delegates would do the same job with a smaller interface. This example belongs in the guide precisely because it's the shape people reach for reflexively once they've learned the pattern, even where the family relationship is thin.

Channel factory bundles sender and receipt writer
flowchart LR A[NotificationService] --> B[IChannelFactory] B --> C[SmtpMessageSender] B --> D[InboxCopyWriter]

3. Document export — report-format families

A reporting module must emit a formatted document plus a matching thumbnail preview, consistently, across PDF and DOCX outputs.

C#
// Reporting/IExportFactory.cs
public interface IExportFactory
{
    IDocumentWriter CreateDocumentWriter();
    IThumbnailRenderer CreateThumbnailRenderer();
}

public sealed class PdfExportFactory : IExportFactory
{
    public IDocumentWriter CreateDocumentWriter() => new PdfDocumentWriter();
    public IThumbnailRenderer CreateThumbnailRenderer() => new PdfThumbnailRenderer();
}

public sealed class ReportExportService(IExportFactory exportFactory)
{
    public async Task<ExportedReport> ExportAsync(ReportModel model, CancellationToken ct)
    {
        var writer = exportFactory.CreateDocumentWriter();
        var thumbnailer = exportFactory.CreateThumbnailRenderer();
        var bytes = await writer.WriteAsync(model, ct);
        var thumbnail = await thumbnailer.RenderAsync(bytes, ct);
        return new ExportedReport(bytes, thumbnail);
    }
}
Export factory produces a matched writer and thumbnailer
flowchart LR A[ReportExportService] --> B[IExportFactory] B --> C[PdfDocumentWriter] B --> D[PdfThumbnailRenderer] C --> E[ExportedReport] D --> E
10

Testing Code That Uses It

Abstract Factory is generally kind to tests: the client depends on an interface, so a fake factory returning fake products is the whole test double. The specific pain is the opposite direction — testing a concrete factory itself tends to duplicate the tests of every product it creates, unless you test only the wiring.

C#
// Tests/CheckoutServiceTests.cs — faking the whole family via one factory
public class CheckoutServiceTests
{
    [Fact]
    public async Task ChargeAsync_uses_gateway_and_vault_from_the_same_factory()
    {
        var gateway = Substitute.For<IChargeGateway>();
        var vault = Substitute.For<ITokenVault>();
        vault.TokenizeAsync(Arg.Any<Card>(), Arg.Any<CancellationToken>())
             .Returns(new Token("tok_123"));
        gateway.ChargeAsync(Arg.Any<Token>(), Arg.Any<decimal>(), Arg.Any<CancellationToken>())
               .Returns(ChargeResult.Success);

        var factory = Substitute.For<IPaymentProviderFactory>();
        factory.CreateChargeGateway().Returns(gateway);
        factory.CreateTokenVault().Returns(vault);

        var sut = new CheckoutService(factory);
        var result = await sut.ChargeAsync(SampleOrder(), CancellationToken.None);

        Assert.Equal(ChargeResult.Success, result);
        await vault.Received(1).TokenizeAsync(Arg.Any<Card>(), Arg.Any<CancellationToken>());
    }
}
C#
// Tests/StripeProviderFactoryTests.cs — integration-level: test only the wiring
[Fact]
public void StripeProviderFactory_creates_a_matched_stripe_family()
{
    var factory = new StripeProviderFactory();

    var gateway = factory.CreateChargeGateway();
    var vault = factory.CreateTokenVault();

    Assert.IsType<StripeChargeGateway>(gateway);
    Assert.IsType<StripeTokenVault>(vault);
    // Deliberately NOT re-testing StripeChargeGateway's charging logic here --
    // that belongs to StripeChargeGateway's own test class.
}
11

When To Use It — And When Not To

Decision tree — is Abstract Factory earning its keep here?
flowchart TD A[Do you have 3+ related products\nthat must vary together?] -->|No| B[Use plain constructor\ninjection or a Func<T>] A -->|Yes| C{Will a new family\nvariant appear again?} C -->|Unlikely, ever| D[A DI container's keyed\nservices probably suffice] C -->|Yes, plausibly| E{Does the container already\nown this object graph?} E -->|Yes| F[Prefer keyed services\nover a bespoke factory] E -->|No / crosses process boundary| G[Abstract Factory\nis a good fit]

Use it when:

  • Three or more products must be created together and swapped as a coherent unit (a UI kit, a regional compliance ruleset, a hardware driver bundle).
  • The family choice is made once, early, and the resulting objects flow through a large surface of unrelated code that shouldn't need to know the choice was made.
  • You need to guarantee — structurally, not by convention — that mismatched family members can never be paired.

Don't use it when:

  • You have exactly two implementations and no third is plausible — an if or a single injected interface is clearer.
  • The "family" has never actually changed in the life of the codebase; you're paying the interface-explosion tax for a variation point that's theoretical.
  • A Func<Order, decimal>-shaped delegate parameter would do the whole job — don't wrap one function in an interface named IPricingStrategyFactory.
  • Your DI container already owns the object graph and keyed services would express the same intent with less ceremony (§6, §12).
  • The indirection will be read primarily by people who won't have this document open next to them — a plain switch in one obvious place can be more honest than an abstraction three files deep.
12

Pros and Cons, Honestly

ProsCons
Guarantees family consistency structurally, not by conventionAdding one product means editing every concrete factory's interface implementation
Isolates concrete-type knowledge to the composition rootAn extra layer of interfaces and classes for what's sometimes just "pick an implementation"
Client code is trivially testable via a fake factoryConcrete factories themselves are awkward to unit test without duplicating product tests
Swapping a family is a one-line change at the composition rootOften reimplements what a DI container's keyed services already do natively

The con list is not shorter than the pros here on purpose — the interface-growth cost is real and unavoidable for the classic form; every genuine advantage above has a matching modern alternative that captures much of it more cheaply.

Contested trade-off: Steven van Deursen and Mark Seemann's Dependency Injection Principles, Practices, and Patterns argues Abstract Factory is frequently overused in DI-based codebases specifically because service abstractions shouldn't expose other service abstractions — a factory interface forces every consumer to depend on both the factory and the products, when the products alone would do. The counter-argument: in genuinely cross-cutting, multi-product families (regional compliance rule sets spanning five or six coordinated services), a structural guarantee of consistency is worth more than the extra dependency, because a keyed-service misconfiguration failure mode — the wrong provider silently paired with the wrong vault — is a production incident, not a compile error. Competent people land differently on where that line sits.

14

Common Mistakes and Anti-Patterns

Mistake 1 — bypassing the factory for "just one" product

C#
// ❌ Wrong — a Windows type sneaks in directly, breaking the family guarantee
public void RenderExtra(IGuiFactory factory)
{
    var button = factory.CreateButton();
    var tooltip = new WindowsTooltip(); // <-- not from the factory
    button.Draw();
    tooltip.Draw();
}
C#
// ✅ Right — the tooltip is added to the factory's contract, or the family
// genuinely doesn't need one and the guide's checklist says so explicitly.
public interface IGuiFactory
{
    IButton CreateButton();
    ICheckbox CreateCheckbox();
    ITooltip CreateTooltip();
}

The rationale: the moment one product bypasses the factory, the pattern's structural guarantee is gone and becomes a convention again — exactly the failure mode from §2's "before" code.

Mistake 2 — a factory interface that grows unrelated responsibilities

C#
// ❌ Wrong — CreateLogger has nothing to do with the UI family
public interface IGuiFactory
{
    IButton CreateButton();
    ICheckbox CreateCheckbox();
    ILogger CreateLogger(); // <-- varies independently, doesn't belong here
}
C#
// ✅ Right — logger is an ordinary injected dependency, unrelated to the family
public sealed class DialogRenderer(IGuiFactory guiFactory, ILogger<DialogRenderer> logger)
{
    // ...
}

Mistake 3 — the subtle one: a "stateless" family factory that isn't

C#
// ❌ Wrong — compiles, passes tests, breaks under concurrent requests months later
public sealed class TenantThemeFactory : IGuiFactory
{
    private string _lastTenantId = ""; // <-- mutable field, registered as Singleton

    public IButton CreateButton() => new TenantButton(_lastTenantId);

    public void SetTenant(string tenantId) => _lastTenantId = tenantId;
}
C#
// ✅ Right — the tenant id is a parameter, not shared mutable state
public sealed class TenantThemeFactory : IGuiFactory
{
    public IButton CreateButton(string tenantId) => new TenantButton(tenantId);
}
// registered as Singleton safely, because it now holds no per-request state

The bug: registered as a DI singleton, _lastTenantId is shared across every concurrent request. Two requests for different tenants racing against each other silently cross-contaminate — it compiles, the single-threaded test suite passes, and it fails only under real concurrent load.

15

Refactoring Path — Introducing It Into Existing Code

Refactoring steps — from the §2 switch to Abstract Factory
flowchart TD A[1. Extract product interfaces\nfrom existing concrete types] --> B[2. Introduce IGuiFactory\nwith one method per product] B --> C[3. Write one concrete factory\nper existing switch branch] C --> D[4. Replace ONE call site's\nswitch with factory.CreateX] D --> E[5. Repeat call-site replacement,\nshippable after each one] E --> F[6. Delete the original switch\nonce no call sites remain]
  1. Extract product interfaces from the existing concrete WindowsButton/MacButton types — this alone is shippable and touches nothing else.
  2. Introduce IGuiFactory with one creation method per product already identified.
  3. Write one concrete factory per existing switch branch — largely mechanical, since the branch bodies already exist.
  4. Replace exactly one call site's switch with a factory call, leaving the rest untouched and the app fully working.
  5. Repeat, one call site per commit — each step is independently reviewable and revertible.
  6. Delete the original switch only once no call site references it — grep for the enum name first.

The seam to cut first is the constructor calls, not the enum — cutting the enum too early leaves every intermediate commit in a broken state. Keep the old UiTheme enum alive through the whole migration; it becomes the factory-selection key at the very end.

ADR template — Introducing Abstract Factory for [family name]
Context: [what varies together, why a switch/if-chain became unmanageable]
Decision: introduce I[Family]Factory with methods [list]; register concrete factories at the composition root keyed by [selection criterion].
Consequences: adding a new product requires updating every concrete factory (accepted cost); adding a new family variant requires only a new factory class and one registration line.
Alternatives considered: keyed DI services (rejected because [reason]); plain Func<T> parameters (rejected because [reason]).

16

Reference Checklist

  • Every product the client touches comes from the factory — no direct new of a concrete family member anywhere outside a concrete factory class.
  • The factory interface contains only creation methods — no unrelated responsibilities (§14, Mistake 2).
  • Concrete factories and products are sealed unless there's a specific reason to allow inheritance.
  • No mutable per-call state lives on a factory registered with a longer lifetime than that state's actual scope (§14, Mistake 3).
  • Before adding a factory interface, keyed DI services and Func<T> parameters have both been considered and rejected for a stated reason.
  • Concrete-factory tests verify wiring only; product behaviour is tested in the product's own test class.
  • The composition root is the only place a family variant is chosen by branching on configuration.
17

Sources

Primary

  • Gamma, Helm, Johnson, Vlissides — Design Patterns: Elements of Reusable Object-Oriented Software (1994), the Abstract Factory chapter.

Analysis and critique

.NET documentation and API references

  • Microsoft Learn — ILoggerFactory and logging providers in ASP.NET Core
  • Microsoft Learn — System.Data.Common.DbProviderFactory
  • Microsoft Learn — keyed services in Microsoft.Extensions.DependencyInjection (.NET 8+)
  • Microsoft — .NET 10 release notes and C# 14 language reference