CreationalC#verifiedVerified

Factory Method Pattern in C#

Defines an interface for creating an object but lets subclasses decide which class to instantiate. Defers instantiation to subclasses.

How to Implement the Factory Method Pattern in C#

1Step 1: Define the Product interface

public interface ITransport
{
    string Deliver(string cargo);
}

2Step 2: Concrete products

public class Truck : ITransport
{
    public string Deliver(string cargo) =>
        $"Delivering '{cargo}' by truck on road";
}

public class Ship : ITransport
{
    public string Deliver(string cargo) =>
        $"Delivering '{cargo}' by ship on sea";
}

3Step 3: Creator declares the factory method

public abstract class Logistics
{
    // Factory Method — subclasses decide which transport to create
    protected abstract ITransport CreateTransport();

    public string PlanDelivery(string cargo)
    {
        var transport = CreateTransport();
        return transport.Deliver(cargo);
    }
}

4Step 4: Concrete creators override the factory method

public class RoadLogistics : Logistics
{
    protected override ITransport CreateTransport() => new Truck();
}

public class SeaLogistics : Logistics
{
    protected override ITransport CreateTransport() => new Ship();
}

// Usage:
// Logistics logistics = new RoadLogistics();
// Console.WriteLine(logistics.PlanDelivery("Electronics"));

Factory Method Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Factory Method Pattern in the Real World

Think of a logistics company that ships packages. The headquarters defines the shipping process but doesn’t decide the vehicle. Regional offices (subclasses) choose whether to use trucks, ships, or drones based on local conditions. The headquarters just says ‘get me a transport’ and the regional office delivers the right one.