Skip to content

Factory Pattern: Abstracting Object Creation

Factory Pattern: Abstracting Object Creation

The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

🏗️ The Problem

Imagine you are building a database migration tool. Initially, you only support SQL Server. Later, you need to add support for PostgreSQL and MySQL. Instead of hardcoding new SqlConnection() or new NpgsqlConnection() throughout your application, you can use a Factory to handle the creation logic in one place.

🚀 The .NET Implementation

In .NET, the Factory pattern is often used to create instances of classes that share a common interface or base class.

1. The Common Interface

public interface IDatabaseConnection
{
    void Connect();
}

2. Concrete Database Connections

public class SqlServerConnection : IDatabaseConnection
{
    public void Connect() => Console.WriteLine("Connecting to SQL Server...");
}

public class PostgresConnection : IDatabaseConnection
{
    public void Connect() => Console.WriteLine("Connecting to PostgreSQL...");
}

3. The Factory Class

public static class ConnectionFactory
{
    public static IDatabaseConnection CreateConnection(string dbType)
    {
        return dbType.ToLower() switch
        {
            "sqlserver" => new SqlServerConnection(),
            "postgres" => new PostgresConnection(),
            _ => throw new NotSupportedException("Database type not supported.")
        };
    }
}

🛠️ Real-World Usage (Client)

// The client doesn't know which concrete class it's using
IDatabaseConnection connection = ConnectionFactory.CreateConnection("postgres");
connection.Connect();

💡 Why use Factory?

  • Decoupling: The client code is decoupled from the concrete classes it uses.
  • Maintainability: All creation logic is in one place. If you add a new database type, you only change the Factory.
  • Testing: You can easily swap the real Factory with a Mock Factory for unit testing.