It is the case where data contains some field indicating what type of strategy should be picked.
I mean, I often ignore solving the problem like shown below and duplicate the problems that strategy pattern is out to solve in the first place. Is there a pattern for it or is it not viable at all in this case?
Recent example on how I have solved it:
public class MapRentalCostStrategy : IMapper<EquipmentType, IRentalCostStrategy>
{
private readonly Dictionary<EquipmentType, IRentalCostStrategy> _knownRentalCostStrategy;
public MapRentalCostStrategy(IMutablePriceConfiguration mutablePriceConfiguration)
{
_knownRentalCostStrategy = new Dictionary<EquipmentType, IRentalCostStrategy>
{
{ EquipmentType.Heavy, new HeavyRentalCostStrategy(mutablePriceConfiguration)},
{ EquipmentType.Specialized, new SpecializedRentalCostStrategy(mutablePriceConfiguration)},
{ EquipmentType.Regular, new RegularRentalCostStrategy(mutablePriceConfiguration)}
};
}
public Func<EquipmentType, IRentalCostStrategy> Create => equipment =>
{
if (!_knownRentalCostStrategy.ContainsKey(equipment))
throw new ArgumentException();
return _knownRentalCostStrategy[equipment];
};
}
where EquipmentType
is an enum.
Maybe I should inject a service that returns this dictionary? In any case, it seems I am delegating the responsibility (in this case its "object creation", it should not be mappers responsibility to deal with the instantiation of the dictionary).
Maybe I am on the wrong track? Is there a better way?
ContainsKey
, useTryGetValue
. \$\endgroup\$