Design Patterns - DanielAceroJuarez/TMSWebAPI GitHub Wiki
The Singleton pattern is used to ensure that a class has only one instance and provides a global point of access to it.
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
is used to achieve Inversion of Control (IoC) between classes and their dependencies.
Startup.cs configures services for dependency injection.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<IRepository<Shipment>, ShipmentRepository>();
}
The Strategy
pattern is used to create a family of algorithms, encapsulate each one, and make them interchangeable.
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
}
}