Mastering Factory Patterns in C#: Simple Factory, Factory Method, and Abstract Factory

Mastering Factory Patterns in C#: Simple Factory, Factory Method, and Abstract Factory

Introduction

Design patterns are fundamental principles in software development that help structure and optimize code. Among the creational patterns, factories play a crucial role in object creation, ensuring flexibility, maintainability, and scalability. In this article, we will explore three popular factory design patterns in C#: Simple Factory, Factory Method, and Abstract Factory. Each pattern provides a different approach to object instantiation, addressing specific scenarios in software development.

Simple Factory

The Simple Factory pattern is a straightforward approach to encapsulating object creation logic. It defines a separate method or class responsible for instantiating objects based on provided parameters. This pattern helps centralize object creation, improving maintainability and reducing coupling.

Implementation in C#

public enum VehicleType
{
    Car,
    Truck
}

public interface IVehicle
{
    void Drive();
}

public class Car : IVehicle
{
    public void Drive() => Console.WriteLine("Driving a car.");
}

public class Truck : IVehicle
{
    public void Drive() => Console.WriteLine("Driving a truck.");
}

public class VehicleFactory
{
    public static IVehicle CreateVehicle(VehicleType type)
    {
        return type switch
        {
            VehicleType.Car => new Car(),
            VehicleType.Truck => new Truck(),
            _ => throw new ArgumentException("Invalid vehicle type")
        };
    }
}

// Usage
IVehicle vehicle = VehicleFactory.CreateVehicle(VehicleType.Car);
vehicle.Drive();        

When to Use

  • When object creation logic needs to be centralized.
  • When dealing with a limited set of object types.

When Not to Use

  • When frequent modifications to object creation logic are expected, leading to frequent updates to the factory.
  • When inheritance is required to extend the factory dynamically.

Factory Method

The Factory Method pattern provides a more flexible approach than the Simple Factory by defining a method that subclasses override to create objects. This allows dynamic creation without modifying the factory itself.

Implementation in C#

public abstract class VehicleFactory
{
    public abstract IVehicle CreateVehicle();
}

public class CarFactory : VehicleFactory
{
    public override IVehicle CreateVehicle() => new Car();
}

public class TruckFactory : VehicleFactory
{
    public override IVehicle CreateVehicle() => new Truck();
}

// Usage
VehicleFactory factory = new CarFactory();
IVehicle vehicle = factory.CreateVehicle();
vehicle.Drive();        

When to Use

  • When different classes need to define their own way of creating objects.
  • When introducing new object types without modifying existing code is essential.

When Not to Use

  • When object creation logic is simple and does not require subclassing.
  • When object instantiation does not require flexibility in subclasses.

Abstract Factory

The Abstract Factory pattern extends the Factory Method pattern by providing an interface for creating families of related objects. This pattern is useful when a system must be independent of how its objects are created, composed, and represented.

Implementation in C#

public interface IVehicleFactory
{
    IVehicle CreateVehicle();
}

public class EconomyVehicleFactory : IVehicleFactory
{
    public IVehicle CreateVehicle() => new Car();
}

public class HeavyVehicleFactory : IVehicleFactory
{
    public IVehicle CreateVehicle() => new Truck();
}

// Usage
IVehicleFactory factory = new EconomyVehicleFactory();
IVehicle vehicle = factory.CreateVehicle();
vehicle.Drive();        

When to Use

  • When multiple related objects need to be created together.
  • When enforcing a consistent creation strategy across multiple object families.

When Not to Use

  • When only one type of object needs to be created.
  • When the complexity of managing multiple factories is unnecessary.

Comparison of Factory Patterns

Each of these factory patterns serves different purposes and has its own advantages and disadvantages:

  • Simple Factory centralizes object creation in a single place, making it easier to maintain. However, adding new object types requires modifying the factory, which can lead to scalability issues.
  • Factory Method introduces an inheritance-based approach where subclasses define object creation. This allows flexibility and expansion but adds complexity by requiring multiple subclasses.
  • Abstract Factory takes it a step further by allowing the creation of entire families of related objects, enforcing consistency across multiple object types. However, this comes with increased complexity and requires more code.

Choosing the right pattern depends on the specific needs of the system. If you need a simple solution for object creation, Simple Factory is a good choice. If you expect to add new types frequently and require flexibility, Factory Method is more suitable. For applications that require families of related objects to be instantiated together, Abstract Factory is the best approach.

Conclusion

Factory patterns provide essential solutions for managing object creation in software development. The Simple Factory is suitable for straightforward scenarios where centralizing object creation simplifies maintenance. The Factory Method offers more flexibility by allowing subclasses to define their own instantiation logic. The Abstract Factory extends this concept further by managing families of related objects systematically. Choosing the right pattern depends on the complexity of the system, the need for extensibility, and the frequency of object type modifications. By applying these patterns effectively, developers can create more scalable, maintainable, and robust software solutions in C#.



João Paulo Ferreira Santos

Data Engineer | AWS | Azure | Databricks | Data Lake | Spark | SQL | Python | Qlik Sense | Power BI

3mo

Great tips!

Like
Reply
João Paulo Ferreira Santos

Data Engineer | AWS | Azure | Databricks | Data Lake | Spark | SQL | Python | Qlik Sense | Power BI

3mo

Great content!

Like
Reply
Gabriel Demétrio Gauche

Full Stack Software Engineer | Front-end focused | ReactJS | React Native | NodeJS | AWS

3mo

Valuable content!

Like
Reply
Aurelio Gimenes

Senior Software Engineer | Java | Spring | Kafka | AWS & Oracle Certified

3mo

Great explanation of the Abstract Factory pattern! This simplifies object creation.

Like
Reply

To view or add a comment, sign in

More articles by Ronilson Silva

Insights from the community

Others also viewed

Explore topics