DEV Community

Cover image for TechTalk 20250611: Factory Pattern - Separating Creation from Use

TechTalk 20250611: Factory Pattern - Separating Creation from Use

At its core, the Factory Pattern centralizes object creation into dedicated methods or classes, instead of scattering new calls or complex constructors throughout your codebase. This separation yields several benefits:

  1. Clarity of Intent
    A method named CreateFromCsv() or ConfigureNumberDisplay() immediately tells the reader what kind of object will emerge, whereas a bare constructor new TextDisplayConfiguration(…) may require you to look up parameter lists and defaults.

  2. Flexible Return Types
    Static factory methods can return any subtype or cached instance they choose. A constructor must always return a fresh instance of its own class.

  3. Simplified Overloads
    Instead of dozens of overloaded constructors to cover different initialization scenarios, you provide a handful of well-named static methods (e.g. WithTitle(), WithSubtitle()), each encapsulating its own logic and defaults.

  4. Validation and Caching
    Factories can centralize validation (throw early on bad arguments), perform expensive setup only once (returning a shared singleton), or even pool and reuse objects.

Static Factory Methods vs Constructors

Aspect Constructors Static Factory Methods
Naming & Discoverability No name beyond class name Method names describe purpose
Return Flexibility Fixed to class it belongs to Can return subtypes or cached refs
Overload Explosion Many overloads → unreadable Distinct methods → self-documented
Default Configuration Logic Scattered in callers Encapsulated in one place
Conditional Instantiation Hard to vary at runtime Easy to branch inside factory

Divooka's Use Case: Organizing Tools by Category

Functions Tray in Divooka - Functions Organized as Categories under Toolboxes

In Divooka, every static method in a class becomes a toolbox entry - with the class name serving as the toolbox category. By grouping related factory methods inside dedicated static class containers (e.g. PlotConfigurations), Divooka can automatically:

  • Discover all available tools at startup
  • Organize them under logical headings (one class = one category)
  • Expose named methods like ConfigureTextDisplayWithTitleAndSubtitle directly to end-users

Were these methods instead constructors on each configuration type, Divooka would lack a natural grouping: you'd have to scan every class for all its constructors, losing that simple "category = class" mapping based on usage.

Case Study: ASP .NET Core's Builder-Based Factory Approach

ASP .NET Core also relies heavily on factories - but often via the builder pattern:

Host.CreateDefaultBuilder(args)
    .ConfigureServices((ctx, services) =>
    {
        services.AddDbContext<MyDbContext>(opts => 
            opts.UseSqlServer(connectionString));
        services.AddSingleton<IMyService, MyService>();
    })
    .Build();
Enter fullscreen mode Exit fullscreen mode

Here the "factory" is implicit in the IHostBuilder:

  • Fluent configuration methods (ConfigureServices, UseUrls, etc.) collect options
  • The final Build() call manufactures the fully wired IHost
  • You get immutability until build time, plus a clear sequence of configuration steps

Comparing Static vs. Builder Factories

Feature Static Factory Methods Builder Pattern (ASP NET Core)
Discovery Simple reflection on static classes Extension-method based; discoverable by IDE but less obvious at runtime
Grouping One class = one category Spread across many fluent calls
Extensibility Add new methods in classes Add new extension methods on interfaces
Configurability Encapsulated per-method logic Centralized in a mutable builder state
Readability Direct: MyFactory.Create(…) Fluent chaining: builder.Configure…

In many small‐to‐medium scenarios, static factory methods win on simplicity: you immediately see each creation scenario, and end-users can invoke exactly what they need. In very large frameworks (like ASP .NET Core), the builder shines by aggregating dozens of configuration concerns into a single, coherent pipeline before creating the final product.

Conclusion

The Factory Pattern - whether via simple static methods or a full builder API - decouples what you need from how it's built. Choosing static factory methods:

  • Keeps creation logic in one readable place
  • Leverages method naming to self-document different initialization paths
  • Allows frameworks like Divooka to auto-discover and categorize tools
  • Avoids constructor overload chaos

Meanwhile, builder-style factories excel when you have large configuration graphs to assemble in a defined sequence. By understanding both approaches, you can pick the pattern that best balances clarity, flexibility, and discoverability in your own projects.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more