Design Patterns

Example 2: Logistics System

In a logistics system, you might need to create different types of transport objects such as trucks, ships, and airplanes. Using the Factory Pattern, you can create a transport factory that generates the appropriate transport type based on the input.

Step 1: Define an interface for transport.

public interface ITransport
{
    void Deliver();
}

Step 2: Implement concrete classes for each transport type.

public class Truck : ITransport
{
    public void Deliver()
    {
        Console.WriteLine("Delivering by land in a truck.");
    }
}

public class Ship : ITransport
{
    public void Deliver()
    {
        Console.WriteLine("Delivering by sea in a ship.");
    }
}

public class Airplane : ITransport
{
    public void Deliver()
    {
        Console.WriteLine("Delivering by air in an airplane.");
    }
}

Step 3: Create a Factory class to generate the appropriate transport object.

public class TransportFactory
{
    public ITransport CreateTransport(string type)
    {
        if (string.IsNullOrEmpty(type))
        {
            return null;
        }

        switch (type.ToUpper())
        {
            case "TRUCK":
                return new Truck();
            case "SHIP":
                return new Ship();
            case "AIRPLANE":
                return new Airplane();
            default:
                return null;
        }
    }
}

Step 4: Use the Factory in the client code.

class Program
{
    static void Main(string[] args)
    {
        TransportFactory factory = new TransportFactory();

        ITransport transport = factory.CreateTransport("TRUCK");
        transport?.Deliver();

        transport = factory.CreateTransport("SHIP");
        transport?.Deliver();

        transport = factory.CreateTransport("AIRPLANE");
        transport?.Deliver();
    }
}