F Factory Method
/
GoF · Creational Pattern

Let subclasses decide which class to build.

Factory Method pushes the decision of which concrete type to instantiate down into a subclass or a delegate, so the code that uses an object never has to name the class it came from. This guide covers the real structure, the C# 14 idioms that have quietly replaced half of it, and the honest argument about whether inheritance-based creation still earns its keep next to a DI container.

17 sections 16 diagrams 21 code samples ~34 min read
Creator.FactoryMethod()
Scroll to explore
01

TL;DR — Intent and the Core Trade-off

Intent, in one sentence: define a method for creating an object, but let the classes that use it defer the actual choice of concrete type to a subclass (or, in modern practice, to a delegate or DI registration) instead of hard-coding new ConcreteThing() everywhere it's needed.

The single rule that defines the pattern: the code that calls the factory method never mentions a concrete product type by name. If a caller writes new SomeConcreteProduct() anywhere near the "factory," the pattern has already been defeated — the whole point is that the decision lives in exactly one place, and everything else programs against the abstraction.

What you buy: new product types can be introduced without touching the code that consumes them — you add a class and, at most, one registration line.

What you pay: an extra layer of indirection and, in its classic inheritance-based form, an extra class per product (one for the product, one for the creator that builds it). In a language with generics, delegates, and a DI container, a good chunk of that cost is now optional — which is exactly the live argument covered in §6 and §12.

Factory Method is the most misunderstood of the five Creational patterns because "factory" gets used loosely for three different things: a bare static method that returns different types based on a parameter (often called Simple Factory and not actually a GoF pattern), the true Factory Method (an overridable creation point tied to a class hierarchy), and Abstract Factory (a family of related factory methods grouped behind one interface). This document is about the middle one — and is explicit, throughout, about where it stops and the other two begin.

02

Origins, Classification, and the Problem It Solves

Classification: Creational, class-scoped (its variation point is inheritance — a subclass overriding a method — rather than an object reference swapped at runtime, which is what makes it structurally different from Strategy despite the similar UML shape). First catalogued in Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, Helm, Johnson, Vlissides), 1994.

It was a reaction to a specific 1994-era C++ and Smalltalk problem: frameworks that wanted to be extensible had no good way to let application code plug in its own object types at the exact point where the framework needed to create something. A drawing framework's Application class needs to create a Document, but the framework author has no idea whether the application wants a TextDocument or a SpreadsheetDocument. Constructors can't be overridden the way methods can, so GoF's answer was: wrap the construction in an ordinary virtual method, and let the subclass override that instead.

The "before" code — the mess this pattern removes

Here's the shape almost everyone has actually written: a method that grows a new if/switch branch every time the business adds a new document export format.

C#
// Reports/ReportExporter.cs — the mess, before Factory Method
public sealed class ReportExporter
{
    public IReportWriter CreateWriter(string format)
    {
        // Every new format means opening this method and adding a branch.
        // Every branch means ReportExporter must know the constructor
        // signature of every writer that has ever existed.
        switch (format)
        {
            case "pdf":
                return new PdfReportWriter(new PdfEngine(), compress: true);
            case "csv":
                return new CsvReportWriter(includeHeaders: true);
            case "xlsx":
                return new ExcelReportWriter(new WorkbookFactory(), "Sheet1");
            case "html":
                return new HtmlReportWriter(inlineStyles: true);
            // ...six sprints later, eight more cases, three of them
            // subtly wrong because nobody remembered the PDF branch
            // needed `compress: true` when they copy-pasted a new one.
            default:
                throw new NotSupportedException($"Unknown format: {format}");
        }
    }
}

The real pain isn't the length of the switch — it's that ReportExporter now has a compile-time dependency on every writer's constructor, so it must be recompiled and redeployed for a format it doesn't otherwise care about, and every caller of CreateWriter is exposed to that churn through the string parameter's silently expanding contract.

03

Structure and Participants

Canonical structure — Creator, ConcreteCreator, Product, ConcreteProduct
classDiagram class Product { <<interface>> +Render() string } class ConcreteProductA { +Render() string } class ConcreteProductB { +Render() string } class Creator { <<abstract>> +FactoryMethod() Product +AnOperation() string } class ConcreteCreatorA { +FactoryMethod() Product } class ConcreteCreatorB { +FactoryMethod() Product } Product <|.. ConcreteProductA Product <|.. ConcreteProductB Creator <|-- ConcreteCreatorA Creator <|-- ConcreteCreatorB Creator ..> Product : creates ConcreteCreatorA ..> ConcreteProductA : returns ConcreteCreatorB ..> ConcreteProductB : returns
ParticipantRoleBelongs in itMust never be in it
ProductThe common interface every created object honoursOnly members every concrete product can genuinely implementMembers only one concrete product needs — that's a leaky abstraction
ConcreteProductOne buildable variantThe behaviour specific to that variantKnowledge of which Creator built it
CreatorDeclares the factory method and uses its result via Product onlyThe workflow/business logic that uses the product (AnOperation)A switch over concrete product types — that's the anti-pattern in §14
ConcreteCreatorOverrides the factory method to return one specific productExactly one new ConcreteProductX() call and nothing elseBusiness logic — that belongs in the base Creator, shared

The membership test: a class is a genuine ConcreteCreator only if the only thing it overrides is the creation decision — if it's also overriding or duplicating business logic from the base Creator, it's not specializing construction, it's forking behaviour, and the pattern has drifted into template-method territory without saying so.

04

The Central Mechanic

The trick is narrower than people expect: the Creator base class calls its own factory method, through itself, without knowing which override will run. That's ordinary virtual dispatch — nothing exotic — but the payoff is that Creator.AnOperation() can be written once, fully generic over the product type, and never touched again as new products appear.

The mechanic — Creator calls its own overridable creation point
flowchart LR A["Creator.AnOperation()"] --> B["this.FactoryMethod()"] B -->|"virtual dispatch<br/>resolves to override"| C["ConcreteCreatorA.FactoryMethod()"] C --> D["new ConcreteProductA()"] D --> E["AnOperation() continues,<br/>coded only against Product"] classDef base fill:transparent,stroke:none,color:inherit; class A,B,E base
C#
// Reports/ReportExporter.cs — the mechanic, smallest possible form
public abstract class ReportExporter
{
    // The factory method: overridable, returns the abstraction only.
    protected abstract IReportWriter CreateWriter();

    // Shared workflow, written once, never touched when a format is added.
    public byte[] Export(ReportData data)
    {
        IReportWriter writer = CreateWriter();   // <-- the mechanic
        writer.Open();
        writer.Write(data);
        return writer.Close();
    }
}

public sealed class PdfReportExporter : ReportExporter
{
    protected override IReportWriter CreateWriter() => new PdfReportWriter();
}

Step through it

Step through — Export() resolves CreateWriter() through virtual dispatch
Clientcaller ReportExporterCreator.Export() PdfReportExporter PdfReportWriterConcreteProduct

05

Implementation in C# — Naive, Then Idiomatic

Pass one: the textbook translation

C#
// Reports/IReportWriter.cs
public interface IReportWriter
{
    void Open();
    void Write(ReportData data);
    byte[] Close();
}

// Reports/ReportExporter.cs — literal GoF translation
public abstract class ReportExporter
{
    protected abstract IReportWriter CreateWriter();

    public byte[] Export(ReportData data)
    {
        IReportWriter writer = this.CreateWriter();
        writer.Open();
        writer.Write(data);
        return writer.Close();
    }
}

public class PdfReportExporter : ReportExporter
{
    protected override IReportWriter CreateWriter()
    {
        return new PdfReportWriter();
    }
}

public class CsvReportExporter : ReportExporter
{
    protected override IReportWriter CreateWriter()
    {
        return new CsvReportWriter();
    }
}

This is deliberately unambitious C#: no primary constructors, no records, explicit access modifiers everywhere. It compiles and works, and it costs one extra class per format — the thing critics point at first (§12).

Pass two: what a .NET 10 developer actually writes in 2026

C#
// Reports/ReportExporter.cs — idiomatic .NET 10 / C# 14
namespace Reports;

public abstract class ReportExporter
{
    // Factory method stays abstract — the variation point is unchanged.
    protected abstract IReportWriter CreateWriter();

    public async Task<byte[]> ExportAsync(ReportData data, CancellationToken ct = default)
    {
        IReportWriter writer = CreateWriter();
        await writer.OpenAsync(ct);
        await writer.WriteAsync(data, ct);
        return await writer.CloseAsync(ct);
    }
}

// A required member + sealed-by-default concrete creator — no ceremony
// beyond the one thing this class actually decides.
public sealed class PdfReportExporter(PdfEngineOptions options) : ReportExporter
{
    protected override IReportWriter CreateWriter() => new PdfReportWriter(options);
}

public sealed class CsvReportExporter : ReportExporter
{
    protected override IReportWriter CreateWriter() => new CsvReportWriter();
}

// Registered by format key — no switch statement anywhere, ever.
// Program.cs
builder.Services.AddKeyedTransient<ReportExporter, PdfReportExporter>("pdf");
builder.Services.AddKeyedTransient<ReportExporter, CsvReportExporter>("csv");
builder.Services.AddKeyedTransient<ReportExporter, ExcelReportExporter>("xlsx");
DivergenceNaive costWhy the idiomatic version wins here specifically
Primary constructor on PdfReportExporterHand-written constructor + field assignment boilerplateThe concrete creator's only job is holding what it needs to build one product — a primary constructor says exactly that, nothing more
sealed by defaultOpen to further inheritance nobody asked forA ConcreteCreator is a leaf in this hierarchy by design; leaving it open invites a second override point that muddies which class decides what
async I/OSynchronous writer calls block a thread per exportEvery real writer touches a stream, a file, or a network call — a 2026 sample that pretends otherwise teaches a bad default
Keyed DI registration instead of a switchA dictionary or switch mapping strings to types, hand-maintainedThe container already knows how to hold a keyed table of implementations — reinventing it duplicates behaviour .NET ships for free
06

Variations and Modern .NET Idioms

VariationShapeWhen it's the better fit
Classic inheritanceAbstract Creator, one subclass per productThe Creator has substantial shared workflow logic beyond just creating the product — subclassing carries real weight
Func<Product> delegateCreator takes a factory delegate in its constructor instead of declaring an abstract methodThe "creator" has no other behavior worth subclassing for — a delegate is a factory method without the ceremony of a type hierarchy
Keyed DI servicesIServiceProvider.GetRequiredKeyedService<T>(key) resolves the product by a runtime keyThe product set is configured, not compiled — new formats are added via container registration, not new source files
Parameterized static method ("Simple Factory")One static method with a switch — not actually GoF Factory MethodGenuinely small, closed, unlikely-to-grow product sets; call it what it is rather than dressing it up as the pattern
C#
// The delegate variation: same intent, no type hierarchy at all.
public sealed class ReportExporter(Func<IReportWriter> createWriter)
{
    public async Task<byte[]> ExportAsync(ReportData data, CancellationToken ct = default)
    {
        IReportWriter writer = createWriter();
        await writer.OpenAsync(ct);
        await writer.WriteAsync(data, ct);
        return await writer.CloseAsync(ct);
    }
}

// Usage — the "factory method" is now just a lambda passed at construction.
var pdfExporter = new ReportExporter(() => new PdfReportWriter(options));

Say it plainly: for a single, unshared creation decision, the delegate form is the modern default in C#. A first-class function type absorbed the ceremony that used to require a subclass. The inheritance-based classic form is now reserved for the case §12 keeps circling back to — where the Creator carries enough shared, overridable workflow that a subclass is pulling its weight for reasons beyond construction.

C#
// The keyed-DI variation resolved by runtime data, not a compiled type choice.
public sealed class ReportExportEndpoint(IServiceProvider services)
{
    public async Task<byte[]> ExportAsync(string format, ReportData data, CancellationToken ct)
    {
        var exporter = services.GetRequiredKeyedService<ReportExporter>(format);
        return await exporter.ExportAsync(data, ct);
    }
}
07

Where .NET Itself Uses It

BCL / ASP.NET Core typeFactory method role
Stream.CanRead / WebRequest.Create(Uri)WebRequest.Create is a textbook Factory Method — the static entry point returns different concrete request types (historically HttpWebRequest, FileWebRequest) based on the URI scheme, resolved through a registered creator per scheme
HttpMessageHandlerBuilder / IHttpClientFactory.CreateClient(name)The named client is the "product"; the factory method is CreateClient, and different registrations act like different ConcreteCreators selected by name
DbProviderFactory.CreateConnection()Textbook Factory Method in ADO.NET — SqlClientFactory, NpgsqlFactory, etc. each override CreateConnection to return their own DbConnection subtype
IHttpClientFactory, ILoggerFactory.CreateLogger(string)Return an abstraction (ILogger) whose concrete type the caller never names — the calling code is coded entirely against the interface
C#
// ILoggerFactory.CreateLogger is a Factory Method the BCL ships:
// the caller never knows or cares which ILogger implementation comes back.
public sealed class OrderService(ILoggerFactory loggerFactory)
{
    private readonly ILogger<OrderService> _log = loggerFactory.CreateLogger<OrderService>();

    public void Place(Order order)
    {
        _log.LogInformation("Placing order {OrderId}", order.Id);
    }
}

// DbProviderFactory: the actual GoF shape, alive in ADO.NET today.
DbProviderFactory factory = DbProviderFactories.GetFactory("Npgsql");
using DbConnection connection = factory.CreateConnection()!;  // <-- factory method
connection.ConnectionString = config.GetConnectionString("Orders");

Worth flagging honestly: DbProviderFactory is the purest textbook example left in the BCL, but most new code reaches for a strongly-typed provider package (Npgsql, Microsoft.Data.SqlClient) directly rather than going through the abstract factory — provider-agnostic ADO.NET code is rarer in practice than the pattern's textbook fame suggests.

C#
// IHttpClientFactory.CreateClient(name) — another BCL Factory Method:
// the concrete HttpClient configuration behind "orders-api" is never
// named at the call site.
public sealed class OrdersApiClient(IHttpClientFactory httpClientFactory)
{
    public async Task<Order?> GetOrderAsync(int id, CancellationToken ct)
    {
        using HttpClient client = httpClientFactory.CreateClient("orders-api");
        return await client.GetFromJsonAsync<Order>($"/orders/{id}", ct);
    }
}
08

Runtime Flows

Happy path

Happy path — export request resolves to a concrete writer
sequenceDiagram participant C as Client participant E as PdfReportExporter participant W as PdfReportWriter C->>E: ExportAsync(data) E->>E: CreateWriter() E->>W: new PdfReportWriter(options) E->>W: OpenAsync() E->>W: WriteAsync(data) W-->>E: bytes E-->>C: byte[] result

Failure path — the factory method itself throws

Failure path — unregistered format at resolution time
sequenceDiagram participant C as Client participant P as IServiceProvider participant E as ReportExporter C->>P: GetRequiredKeyedService<ReportExporter>("tiff") P-->>C: InvalidOperationException<br/>(no service registered for key "tiff") Note over C: Caller must handle at the<br/>resolution boundary, not deep<br/>inside Export()

A structurally interesting path — swapping the creator behind an interface at startup

Configuration-driven creator selection at composition root
sequenceDiagram participant Host as Program.cs participant Cfg as IConfiguration participant DI as IServiceCollection participant App as OrderPipeline Host->>Cfg: Read "Export:DefaultFormat" Cfg-->>Host: "xlsx" Host->>DI: AddKeyedTransient<ReportExporter, ExcelReportExporter>("xlsx") Note over Host,DI: All ConcreteCreators are still<br/>registered — only the *default*<br/>key changes with config App->>DI: GetRequiredKeyedService<ReportExporter>(defaultKey) DI-->>App: ExcelReportExporter instance
09

Real-World Worked Examples — Three

1. Notification channel creation (notifications domain)

A platform sends order updates over email, SMS, or push, and needs to add channels over time without editing a dispatcher every time.

C#
// Notifications/NotificationDispatcher.cs
public abstract class NotificationDispatcher
{
    protected abstract INotificationChannel CreateChannel();

    public async Task SendAsync(NotificationMessage msg, CancellationToken ct)
    {
        INotificationChannel channel = CreateChannel();
        await channel.SendAsync(msg, ct);
    }
}

public sealed class EmailNotificationDispatcher(IEmailClient client) : NotificationDispatcher
{
    protected override INotificationChannel CreateChannel() => new EmailChannel(client);
}

public sealed class SmsNotificationDispatcher(ISmsGateway gateway) : NotificationDispatcher
{
    protected override INotificationChannel CreateChannel() => new SmsChannel(gateway);
}
Notification dispatch through per-channel creators
flowchart LR A[OrderPlaced event] --> B{Preferred channel?} B -->|email| C[EmailNotificationDispatcher] B -->|sms| D[SmsNotificationDispatcher] C --> E[EmailChannel] D --> F[SmsChannel]

2. Payment processor selection (payments domain)

An e-commerce backend must build the correct payment gateway client for the merchant's configured provider.

C#
// Payments/PaymentCheckout.cs
public abstract class PaymentCheckout
{
    protected abstract IPaymentProcessor CreateProcessor();

    public async Task<PaymentResult> ChargeAsync(Order order, CancellationToken ct)
    {
        IPaymentProcessor processor = CreateProcessor();
        return await processor.ChargeAsync(order.Total, order.Currency, ct);
    }
}

public sealed class StripeCheckout(StripeOptions options) : PaymentCheckout
{
    protected override IPaymentProcessor CreateProcessor() => new StripeProcessor(options);
}

// Program.cs — resolved by merchant configuration, not a switch
builder.Services.AddKeyedTransient<PaymentCheckout, StripeCheckout>("stripe");
builder.Services.AddKeyedTransient<PaymentCheckout, PayPalCheckout>("paypal");
Merchant-configured payment processor resolution
flowchart LR A[Checkout request] --> B[Resolve keyed PaymentCheckout] B --> C[StripeCheckout] B --> D[PayPalCheckout] C --> E[StripeProcessor] D --> F[PayPalProcessor]

3. Device I/O — where Factory Method is an uncomfortable fit

A warehouse app talks to barcode scanners from three vendors. The temptation is a ScannerFactory hierarchy — but the vendors' SDKs differ not just in construction but in connection lifecycle, error codes, and threading model, so the "shared workflow" the base Creator is supposed to hold barely exists.

C#
// Devices/ScannerSession.cs — the awkward-fit version
public abstract class ScannerSession
{
    protected abstract IBarcodeScanner CreateScanner();

    // This "shared" method ends up almost empty, because everything
    // interesting — reconnect policy, timeout handling — differs per vendor
    // and gets pushed back down into overrides anyway.
    public async Task<string> ScanOnceAsync(CancellationToken ct)
    {
        IBarcodeScanner scanner = CreateScanner();
        return await scanner.ReadAsync(ct);
    }
}

public sealed class ZebraScannerSession(ZebraSdkOptions opts) : ScannerSession
{
    protected override IBarcodeScanner CreateScanner() => new ZebraScanner(opts);
    // ...but Zebra's reconnect logic needs its own override too,
    // and now the "shared" base class is shared in name only.
}

This is the honest case: when the base class ends up as a thin pass-through because every vendor needs its own everything, Factory Method is providing an interface (worth keeping) without much of a workflow to share (the actual justification for the inheritance). A per-vendor adapter registered in DI, without the shared abstract base, is arguably a better fit — see §11.

C#
// The arguably-better fit: a plain adapter behind keyed DI,
// no shared abstract Creator carrying almost nothing.
public interface IBarcodeScanner { Task<string> ReadAsync(CancellationToken ct); }

public sealed class ZebraScannerAdapter(ZebraSdkOptions opts) : IBarcodeScanner
{
    public Task<string> ReadAsync(CancellationToken ct) => ZebraSdk.ReadWithRetryAsync(opts, ct);
}

builder.Services.AddKeyedSingleton<IBarcodeScanner, ZebraScannerAdapter>("zebra");
Device session — thin shared base, most logic pushed to overrides
flowchart TB A[ScannerSession.ScanOnceAsync] --> B[CreateScanner override] B --> C[ZebraScannerSession] B --> D[HoneywellScannerSession] C --> E["Zebra reconnect logic<br/>lives here, not shared"] D --> F["Honeywell reconnect logic<br/>lives here, not shared"]
10

Testing Code That Uses It

Factory Method generally helps testability compared to hard-coded new calls, because the abstraction seam is already there — but it introduces its own specific pain: tests that only exercise the base Creator workflow can't verify which concrete product a given ConcreteCreator actually builds without either subclassing for the test or reaching into implementation details.

C#
// Tests/PdfReportExporterTests.cs — xUnit
public class PdfReportExporterTests
{
    [Fact]
    public void CreateWriter_returns_a_PdfReportWriter()
    {
        // Exposing the factory method as `internal` + [InternalsVisibleTo]
        // (or `protected internal` with a test subclass) is the pragmatic
        // way to assert *which* concrete product came back.
        var exporter = new TestablePdfReportExporter(new PdfEngineOptions());

        var writer = exporter.ExposedCreateWriter();

        Assert.IsType<PdfReportWriter>(writer);
    }

    private sealed class TestablePdfReportExporter(PdfEngineOptions options)
        : PdfReportExporter(options)
    {
        public IReportWriter ExposedCreateWriter() => CreateWriter();
    }
}

// Integration-level: verify the shared workflow end-to-end against a fake product.
public class ReportExporterWorkflowTests
{
    [Fact]
    public async Task ExportAsync_opens_writes_then_closes_in_order()
    {
        var spyWriter = new SpyReportWriter();
        var exporter = new FakeReportExporter(() => spyWriter);

        await exporter.ExportAsync(new ReportData());

        Assert.Equal(
            new[] { "Open", "Write", "Close" },
            spyWriter.CallOrder);
    }

    private sealed class FakeReportExporter(Func<IReportWriter> factory) : ReportExporter
    {
        protected override IReportWriter CreateWriter() => factory();
    }
}

The delegate-based variation (§6) sidesteps the "protected method" testing friction entirely — a Func<IReportWriter> passed into the constructor can be a test spy directly, with no subclassing required.

11

When To Use It — And When Not To

Decision tree — Factory Method or something simpler
flowchart TD A["Need to vary which<br/>concrete type gets built?"] -->|No| B["Just call new — no pattern needed"] A -->|Yes| C["Does the creator also carry<br/>real shared workflow logic?"] C -->|No| D["Use a Func<T> delegate<br/>or DI registration directly"] C -->|Yes| E["Will more product types<br/>plausibly be added later?"] E -->|No, fixed set of 2| F["A simple if/switch is honest<br/>and cheaper than a hierarchy"] E -->|Yes| G["Factory Method:<br/>abstract Creator + ConcreteCreators"]
Use it whenDon't use it when
New product types are a recurring, expected event (new export format, new payment gateway)You have exactly two implementations and no third is plausible in the codebase's realistic lifetime
The Creator has meaningful shared workflow beyond just building the productThe "shared workflow" is one line — a Func<T> parameter does the whole job with less ceremony
A framework needs to let downstream code plug in its own types without the framework knowing about themThe variation has never actually changed in three years of the codebase's life — you're paying for flexibility nobody used
The product's construction genuinely differs enough per type that a switch would grow unmanageablyThe indirection will be read primarily by people unfamiliar with this pattern's vocabulary, and a direct if would be more legible to them
C#
// "Don't use it" in practice: two fixed implementations, no third coming.
// A direct branch is more honest than a Creator hierarchy for this.
public sealed class InvoiceNumberFormatter
{
    public string Format(InvoiceNumberStyle style, int number) => style switch
    {
        InvoiceNumberStyle.Sequential => number.ToString("D6"),
        InvoiceNumberStyle.YearPrefixed => $"{DateTime.UtcNow:yyyy}-{number:D4}",
        _ => throw new ArgumentOutOfRangeException(nameof(style))
    };
}
12

Pros and Cons, Honestly

ProsCons
Adding a product type never requires editing existing, working code (Open/Closed in practice)One extra class per product in the classic form — real cost, not imagined
Client code is coded entirely against the abstraction — no concrete-type leakageAn extra layer of indirection a reader has to trace through to find out what's actually built
Plays well with frameworks: third parties can plug in types the framework author never anticipatedStatic/inheritance-based — the choice of product is usually fixed once a concrete Creator is chosen, not swappable per call
Testable: the creation seam already exists without extra refactoringEasy to over-apply to product sets that will never actually grow, paying complexity for flexibility that's never exercised

Contested trade-off, stated as a disagreement: does Factory Method survive dependency injection? One camp (see Mark Seemann and Steven van Deursen's writing on DI anti-patterns) argues Abstract Factories — and by extension much of classic Factory Method — are frequently misapplied as a workaround for DI containers that can't select an implementation based on runtime data, when the actual fix is to inject the decision differently (a strategy keyed at composition time, not resolved deep inside a consumer). The counter-argument: a DI container resolves the *set* of registered types at startup, but it can't express "pick this specific one based on data only known at the point of use" without either a factory abstraction or a service locator — and a factory method is the more testable, more explicit of those two escape hatches. Both sides agree service-locator-style resolution deep inside business logic is worse than either.

14

Common Mistakes and Anti-Patterns

Mistake 1 — a switch statement hiding inside "the factory"

C#
// ❌ Wrong — this "Creator" still has the exact switch it was meant to remove.
public abstract class ReportExporter
{
    protected IReportWriter CreateWriter(string format) => format switch
    {
        "pdf" => new PdfReportWriter(),
        "csv" => new CsvReportWriter(),
        _ => throw new NotSupportedException(format)
    };
}

// ✅ Right — the switch is gone because the decision moved to the type hierarchy.
public abstract class ReportExporter
{
    protected abstract IReportWriter CreateWriter();
}
public sealed class PdfReportExporter : ReportExporter
{
    protected override IReportWriter CreateWriter() => new PdfReportWriter();
}

The rationale: renaming a Simple Factory's switch to CreateWriter doesn't make it a Factory Method — the tell is whether adding a product requires editing existing code. If it does, the pattern hasn't actually been applied yet.

Mistake 2 — the base Creator reaching into concrete product state

C#
// ❌ Wrong — Creator downcasts to reach a member Product doesn't declare.
public byte[] Export(ReportData data)
{
    var writer = CreateWriter();
    if (writer is PdfReportWriter pdf) pdf.SetCompressionLevel(9); // leak!
    writer.Open(); writer.Write(data); return writer.Close();
}

// ✅ Right — anything every writer needs belongs on IReportWriter itself.
public interface IReportWriter
{
    void Open();
    void Write(ReportData data);
    byte[] Close();
    void Configure(WriterOptions options); // shared, not PDF-specific
}

Mistake 3 (the subtle one) — a "shared" base workflow that silently assumes one product's semantics

C#
// ❌ Wrong — compiles, passes tests written against PdfReportExporter,
// breaks silently for a streaming writer that can't buffer everything.
public byte[] Export(ReportData data)
{
    var writer = CreateWriter();
    writer.Open();
    writer.Write(data);
    var bytes = writer.Close();
    File.WriteAllBytes(TempPath, bytes); // assumes "small enough to hold in memory"
    return bytes;
}

// ✅ Right — the shared method makes no assumption beyond the interface contract.
public async Task<byte[]> ExportAsync(ReportData data, CancellationToken ct)
{
    var writer = CreateWriter();
    await writer.OpenAsync(ct);
    await writer.WriteAsync(data, ct);
    return await writer.CloseAsync(ct); // caller decides what to do with the bytes
}

This one hurts six months later specifically because it works fine for every product that happens to produce small in-memory output, until a streaming export format is added and the assumption baked into the "shared" method silently corrupts or truncates its output.

Anti-pattern: a switch reappearing inside the factory method
flowchart LR A[CreateWriter format] --> B{switch on format string} B -->|pdf| C[new PdfReportWriter] B -->|csv| D[new CsvReportWriter] B -->|default| E[throw NotSupportedException] style B fill:transparent
Anti-pattern: shared workflow silently coupled to one product's assumptions
flowchart TB A[Export shared workflow] --> B[Assumes output fits in memory] B --> C[Works: PdfReportWriter, CsvReportWriter] B --> D["Breaks silently: StreamingParquetWriter<br/>added eight months later"]
15

Refactoring Path — Introducing It Into Existing Code

Starting from the §2 switch statement, here's an ordered path where every step ships independently and the app keeps working the whole way through.

Refactoring steps — from switch to Factory Method
flowchart TD A["1. Extract IReportWriter<br/>from the branches' shapes"] --> B["2. Extract each branch's<br/>body into its own ConcreteProduct"] B --> C["3. Introduce abstract<br/>ReportExporter.CreateWriter()"] C --> D["4. Move each branch into<br/>its own ConcreteCreator override"] D --> E["5. Register ConcreteCreators<br/>in DI, keyed by format"] E --> F["6. Delete the original<br/>switch statement"]
  1. Cut the first seam: extract an IReportWriter interface from what the branches already have in common (an Open/Write/Close shape usually falls out immediately). No behaviour changes yet — this step is purely a signature extraction and should be a no-diff-in-behaviour commit.
  2. Extract each branch body into its own class implementing that interface, one commit per format so a bad extraction is easy to isolate and revert.
  3. Introduce the abstract Creator with a single abstract CreateWriter() method and the shared workflow moved onto it, still called from the same call sites via the old ReportExporter.CreateWriter(string format) entry point as a thin compatibility shim.
  4. Move each switch branch into its own ConcreteCreator override, one at a time — existing call sites keep working because the shim still dispatches on the string.
  5. Register the ConcreteCreators in DI, keyed by format, and change call sites one by one to resolve through the container instead of the shim.
  6. Delete the shim and the original switch once nothing references it — verify with a repo-wide search for the old method name before removing it.

Keeping it reviewable: land steps 1–2 as a pure-refactor PR with no behaviour change (green tests, no new registrations), then land 3–6 as a second PR that a reviewer can read purely as "wiring," since the hard part (the extraction) is already merged and stable.

ADR fieldContent for this refactor
TitleIntroduce Factory Method for report writer creation
StatusProposed / Accepted
ContextReport format selection is a growing switch statement coupling ReportExporter to every writer's constructor
DecisionExtract IReportWriter, introduce an abstract ReportExporter.CreateWriter(), register concrete exporters as keyed DI services
ConsequencesNew formats require one class + one registration line, not an edit to ReportExporter; adds one interface and N small classes to the codebase
16

Reference Checklist

  • The factory method returns the Product abstraction, never a concrete type, from its signature.
  • No switch or if-chain over concrete product types survives anywhere near "the factory."
  • Each ConcreteCreator does exactly one thing: build and return one product type.
  • Shared workflow in the base Creator makes no assumption that holds for only some products.
  • Before reaching for the inheritance-based form, a Func<T> delegate or keyed DI registration has been considered and rejected for a stated reason.
  • New product types can be added without editing the base Creator or any existing ConcreteCreator.
  • Tests can verify which concrete product a given creator builds without reflection hacks.
  • The pattern isn't applied to a product set that has never actually grown and shows no sign of needing to.
17

Sources

Primary

  • Gamma, Helm, Johnson, Vlissides — Design Patterns: Elements of Reusable Object-Oriented Software (1994), the original Factory Method catalog entry.

Analysis and critique

.NET documentation and API references