Design Patterns - DanielAceroJuarez/TMSWebAPI GitHub Wiki

Design Patterns

Singleton

The Singleton pattern is used to ensure that a class has only one instance and provides a global point of access to it.

Implementation

ShipmentManager is implemented as a singleton.

public sealed class ShipmentManager
{
    private static readonly ShipmentManager _instance = new ShipmentManager();
    private ShipmentManager() { }
    public static ShipmentManager Instance => _instance;
}

Dependency Injection

Dependency Injection is used to achieve Inversion of Control (IoC) between classes and their dependencies.

Implementation

Startup.cs configures services for dependency injection.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSingleton<IRepository<Shipment>, ShipmentRepository>();
}

Strategy

The Strategy pattern is used to create a family of algorithms, encapsulate each one, and make them interchangeable.

Implementation

Shipping cost calculation strategies are implemented using the Strategy pattern.

public interface IShippingStrategy
{
    decimal CalculateShippingCost(Shipment shipment);
}

public class StandardShippingStrategy : IShippingStrategy
{
    public decimal CalculateShippingCost(Shipment shipment)
    {
        return shipment.Weight * 1.5m; // Example rate
    }
}

public class ExpressShippingStrategy : IShippingStrategy
{
    public decimal CalculateShippingCost(Shipment shipment)
    {
        return shipment.Weight * 2.5m; // Example rate
    }
}
⚠️ **GitHub.com Fallback** ⚠️