Strategy in a design: parking fees

Keep the parking lot closed for change while fee rules keep changing, by putting the rule behind an interface.

Time —Space —Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

When one step has several interchangeable rules, put the rule behind an interface and give the context an instance of it. Adding a weekend rate becomes a new class; ParkingLot is never edited.

Code

public interface IFeeStrategy { decimal Fee(TimeSpan stay); }
public class HourlyFee : IFeeStrategy
{ public decimal Fee(TimeSpan s) => 40m * (decimal)Math.Ceiling(s.TotalHours); }
public class DailyCapFee : IFeeStrategy
{ public decimal Fee(TimeSpan s) => Math.Min(300m, 40m * (decimal)Math.Ceiling(s.TotalHours)); }
public class ParkingLot
{
    readonly IFeeStrategy _fee;
    public ParkingLot(IFeeStrategy fee) => _fee = fee;
    public decimal Exit(Ticket t) => _fee.Fee(DateTime.UtcNow - t.Entered);
}

Tips

In the .NET library

builder.Services.AddSingleton<IFeeStrategy, DailyCapFee>(); then ParkingLot receives it through its constructor.