考慮一個生成生產計劃的應用程序(下面的簡化代碼示例)。有很多產品清單,我們多次調用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