在这种情况下,数据包含一些字段,指示应该选择哪种类型的策略。
我的意思是,我经常忽略解决下面所示的问题,重复策略模式首先要解决的问题。在这种情况下,它是否有一个模式,或者根本不可行?
最近关于我如何解决这个问题的例子:
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];
};
}其中EquipmentType是一个枚举。
也许我应该注入一个返回此字典的服务?无论如何,我似乎是在委派责任(在这种情况下,它的“对象创建”,不应该是映射者处理字典实例化的责任)。
也许我走错路了?有更好的办法吗?
发布于 2016-05-19 16:49:21
我认为单例/枚举模式将是有益的。奇怪的是,IMutablePriceConfiguration对象似乎因情况而异。
将IMutablePriceConfiguration作为成本策略对象的依赖项删除。
下一步:
public sealed class EquipmentType
{
public static readonly Heavy = new EquipmentType(1, "Heavy", new HeavyRentalCostStrategy());
public static readonly Specialized = new EquipmentType(2, "Specialized", new SpecializedRentalCostStrategy());
public static readonly Regular = new EquipmentType(3, "Regular", new RegularRentalCostStrategy());
public static readonly IEnumerable<EquipmentType> All = new EquipmentType[]
{
Heavy,
Specialized,
Regular
};
public static EquipmentType Find(int id)
{
return All.SingleOrDefault(e => e.Id == id);
}
public static EquipmentType Find(string name)
{
return All.SingleOrDefault(e => e.Name == name);
}
private IRentalCostStrategy CostStrategy { get; set; }
public string Name { get; private set; }
public int Id { get; private set; }
private EquipmentType(int id, string name, IRentalCostStrategy costStrategy)
{
Id = id;
Name = name;
CostStrategy = costStrategy;
}
public double CalculateRentalCost(IMutablePriceConfiguration mutablePriceConfiguration)
{
return CostStrategy.CalculateRentalCost(mutablePriceConfiguration);
}
}IMutablePriceConfiguration成为EquipmentType类上的CalculateRenderCost方法的参数。IMutablePriceConfiguration对象,就可以盲目地调用CalculateRentalCost方法并获得结果。不需要ifs或switchs到处都是你的代码。https://codereview.stackexchange.com/questions/128735
复制相似问题