目前,我有一堆if else语句来根据每个集合中有多少项来设置CategoryId。
例如,
public class TeamWork
{
public string EmployeeName { get; set; }
public int CategoryId { get; set; }
}
public class BLL
{
public void SetCategoryId(ICollection<TeamWork> Converted, ICollection<TeamWork> Sourced)
{
if (Converted.Count == 1 && Sourced.Count == 1)
{
if (String.Compare(Sourced.First().EmployeeName, Converted.First().EmployeeName) == 0)
{
// set category id to 1
Converted.First().CategoryId = 1;
Sourced.First().CategoryId = 1;
}
else
{
// set category id to something
}
}
else if (Sourced.Rows.Count == 1 && Converted.Rows.Count > 1)
{
// set category id to something
}
// more if else statements...
}
}我认为有一种更好的方法可以做到这一点,也许是通过应用一些设计模式。有什么建议吗?谢谢!
发布于 2011-03-18 00:09:18
Chain of responsibility是最好的选择。
因此,此对象被传递给一系列命令对象,直到一个对象能够执行操作并设置状态。
发布于 2011-03-18 00:10:05
脑海中浮现出一种策略模式。尝试将这些规则分解为一系列“如果此条件为真,则类别ID为此”。使每个方法都成为方法,然后将这些方法作为委托添加到List<Func<ICollection<TeamWork>, ICollection<TeamWork>, bool>>或类似的索引集合中。然后,您的SetCategoryId()代码如下所示:
public void SetCategoryId(ICollection<TeamWork> Converted, ICollection<TeamWork> Sourced)
{
foreach(var categoryRule in CategoryRules)
{
var category = test(Converted, Sourced);
if(category != 0)
{
Converted.First().CategoryId = Sourced.First().CategoryId = category;
break;
}
}
}无论您添加或删除了多少规则,上面的代码都不需要更改。但是,使用if - else if结构,您的一系列规则可能依赖于顺序,因此在列表中设置规则时要小心。
https://stackoverflow.com/questions/5341696
复制相似问题