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.
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
- This is the open/closed principle in practice: open for new rules, closed for modification.
- Pick the strategy with configuration or a small factory, and register it in dependency injection.
- Strategy versus State: with Strategy the caller chooses the rule; with State the object changes it by itself.
In the .NET library
builder.Services.AddSingleton<IFeeStrategy, DailyCapFee>(); then ParkingLot receives it through its constructor.