考虑一个生成生产计划的应用程序(下面的简化代码示例)。有很多产品清单,我们多次调用product.GetProductionTime(),同时在生产计划中进行复杂的计算。我们需要product.GetProductionTime()根据我们正在使用的规划算法或我们所使用的算法的步骤而有所不同.GetProductionTime()中的条件很难看,并且添加另一个算法并不容易。你会在这里实施一个战略模式吗?如果是,如何?
我在考虑策略模式。这是一个实施它的好地方吗?如果是的话,你会如何执行它?如果不是,我该怎么办?
public class ProductionPlanningProblem
{
public List<Product> Products;
public void GenerateFastProdPlan()
{
foreach (Product product in Products)
{
//do lots of calculations
product.GetProductionTime(PlanType.Fast);
//do lots of calculations
}
}
public void GenerateSlowProdPlan()
{
foreach (Product product in Products)
{
//do lots of calculations
product.GetProductionTime(PlanType.Slow);
//do lots of calculations
}
}
}
public class Product
{
public int GetProductionTime(Plantype plantype)
{
if(plantype.Fast)
return CalculationFast();
if (plantype.Slow && SomeOtherConditionsHold)
return CalculationSlow();
return CalculationFast();
}
private int CalculationFast()
{
//do fast calculation depending on many fields of product
return result;
}
private int CalculationSlow()
{
//do slow but more accurate calculations depending on many fields of product
return result;
}
}
PLZ提供了一个例子来解释它更好 – 2012-10-26 13:32:25