GitHub logo SebastianDevelops / DesignPatterns

Work in progress: Visually displaying design patterns

Factory Method Design Pattern in C# ...

🏭 Design Patterns – Beginner-Friendly Guide

If you're looking to understand Design Patterns in with real-world examples, you've come to the right place. This guide breaks down the pattern's structure, benefits, and practical applications.

📘 Visual Step-by-Step Guide

For a visual walkthrough of the Factory Design Pattern, including diagrams and code examples, visit:

👉 sebastiandevelops.github.io/DesignPatterns

This resource offers an interactive experience to reinforce your understanding of the pattern.

📄 Article Overview

In the accompanying article, you'll learn: (Factory Design Pattern In C# - C# Corner)

  • The fundamentals of the Factory Design Pattern.
  • How to implement the pattern in C#.
  • Real-world scenarios where the pattern is beneficial.
  • Best practices and common pitfalls to avoid.

The article is designed to be beginner-friendly, ensuring that you can grasp the concepts even if you're new to design patterns.

🔗 Additional Resources

To further enhance your understanding, consider exploring these resources:

Here’s a deep-dive, beginner-friendly guide to the Factory design pattern in C#, complete with real-world examples, code snippets, and best-practices. You’ll learn what problem it solves, how to implement it, and how it fits into modern application architectures like dependency injection and provider-agnostic data access.

Summary

The Factory Method is a creational design pattern that defines an interface for creating objects but lets subclasses decide which concrete classes to instantiate, thereby decoupling client code from specific implementations (Factory Method - Refactoring.Guru). In C#, you typically declare an abstract Creator with a factory method, then implement ConcreteCreators that override it to produce ConcreteProducts (C# Factory Method Design Pattern - Dofactory.com). This pattern enhances flexibility, maintainability, and testability by centralizing object-creation logic and supporting dependency injection scenarios (Design Patterns: Dependency Injection | Microsoft Learn). Real-world uses range from document generators and UI component libraries to database-provider factories in ADO.NET (Factory Model Overview - ADO.NET | Microsoft Learn).

What Is the Factory Method Pattern?

The Factory Method pattern provides an interface for creating objects in a superclass, while allowing subclasses to alter the type of objects that will be created (Factory Method - Refactoring.Guru). Rather than calling constructors (new) directly, client code calls a factory method; subclasses override that method to return different concrete types (Factory Method in C# / Design Patterns - Refactoring.Guru).

Problem It Solves

Imagine a logistics app originally hard-coded to use Truck objects. Adding Ship or Airplane would force changes across the codebase, violating the Open/Closed Principle (Factory Method - Refactoring.Guru). The Factory Method centralizes construction logic so new transport types plug in without touching existing code.

Structure and Participants

Typical roles in the Factory Method pattern:

// Creator
public abstract class DocumentCreator {
    public abstract IDocument CreateDocument();
    public void Render() {
        var doc = CreateDocument();
        doc.Print();
    }
}

// ConcreteCreator
public class PdfDocumentCreator : DocumentCreator {
    public override IDocument CreateDocument() => new PdfDocument();
}

// Product
public interface IDocument {
    void Print();
}

// ConcreteProduct
public class PdfDocument : IDocument {
    public void Print() => Console.WriteLine("Printing PDF");
}

C# Examples

Structural Example

The DOFactory structural example shows the pattern’s skeleton: an abstract Product, concrete products, an abstract Creator with FactoryMethod(), and concrete creators overriding it (C# Factory Method Design Pattern - Dofactory.com).

Real-World Example: Document Generator

In a resume/report generator, the base Document constructor calls an abstract CreatePages() factory method; subclasses (Resume, Report) add page types (C# Factory Method Design Pattern - Dofactory.com). This ensures each document assembles the right pages without client code knowing specifics.

abstract class Document {
    protected List<Page> Pages = new();
    public Document() => CreatePages();
    public abstract void CreatePages();
}

class Resume : Document {
    public override void CreatePages() {
        Pages.Add(new SkillsPage());
        Pages.Add(new EducationPage());
        Pages.Add(new ExperiencePage());
    }
}

Benefits

Real-World Application Scenario

Credit Card Processing System

A payment gateway might support multiple card types (Visa, MasterCard, Amex). A CardFactory reads a config or input string and returns the appropriate ICreditCard implementation. Client code processes the ICreditCard without knowing its concrete type (Factory Design Pattern in C# with Examples - Dot Net Tutorials).

public static class CardFactory {
    public static ICreditCard GetCard(string cardType) =>
        cardType switch {
            "Visa" => new VisaCard(),
            "Master" => new MasterCard(),
            _ => throw new ArgumentException("Unknown card")
        };
}

Integration with Dependency Injection

You can register factory delegates or factory classes in your DI container (e.g., Microsoft.Extensions.DependencyInjection). Instead of injecting concrete types, inject a Func that resolves the right implementation at runtime (Design Patterns: Dependency Injection | Microsoft Learn).

services.AddTransient<VisaCard>();
services.AddTransient<MasterCard>();
services.AddSingleton<Func<string, ICreditCard>>(sp => key => 
    key == "Visa" ? sp.GetService<VisaCard>() : sp.GetService<MasterCard>());

Factory in Data-Provider-Agnostic Code

ADO.NET’s DbProviderFactories uses the Factory pattern to create provider-specific objects (connections, commands) from a single API, enabling database-agnostic data access (Factory Model Overview - ADO.NET | Microsoft Learn).

When to Use & Best Practices

Conclusion

The Factory Method is a cornerstone of creational patterns in C#, promoting loose coupling, scalability, and maintainability. By centralizing instantiation logic, it simplifies extension and testing. In modern .NET apps you’ll often see it wrapped by DI containers or used in provider-agnostic frameworks like ADO.NET.