skip to content
Mohammad Rebati

Understanding the Factory Method Design Pattern

/ 2 min read

Introduction to the Factory Method Design Pattern

The Factory Method Design 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. This pattern is particularly useful when there is a need to delegate the instantiation process to child classes.

Key Concepts

  • Creator: An abstract class or interface that declares the factory method, which returns an object of a Product class.
  • Concrete Creator: A class that implements or extends the Creator class and overrides the factory method to return an instance of a Concrete Product.
  • Product: An interface or abstract class that defines the objects the factory method creates.
  • Concrete Product: A subclass of Product that implements the product interface.

Benefits

  • Flexibility: Subclasses can alter the class of objects that will be created independently from the client.
  • Encapsulation: Clients are decoupled from the actual concrete classes needed to create instances, relying solely on interfaces.

Example in Code

Here’s how you might implement the Factory Method Pattern in C# within a logistics management system where different types of transportation are needed:

// Product interface
public interface ITransport
{
void Deliver();
}
// Concrete Products
public class Truck : ITransport
{
public void Deliver()
{
Console.WriteLine("Deliver by land in a box");
}
}
public class Ship : ITransport
{
public void Deliver()
{
Console.WriteLine("Deliver by sea in a container");
}
}
// Creator class
public abstract class Logistics
{
public abstract ITransport CreateTransport();
public void PlanDelivery()
{
ITransport transport = CreateTransport();
transport.Deliver();
}
}
// Concrete Creator
public class RoadLogistics : Logistics
{
public override ITransport CreateTransport()
{
return new Truck();
}
}
public class SeaLogistics : Logistics
{
public override ITransport CreateTransport()
{
return new Ship();
}
}
// Example usage
class Program
{
static void Main(string[] args)
{
Logistics logistics = new RoadLogistics();
logistics.PlanDelivery();
logistics = new SeaLogistics();
logistics.PlanDelivery();
}
}