C# 需要帮助选择设计模式吗
目前,我有一组if-else语句,用于根据每个集合中的项目数设置CategoryId 比如说,C# 需要帮助选择设计模式吗,c#,.net,design-patterns,C#,.net,Design Patterns,目前,我有一组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, IC
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...
}
}
公共课堂团队合作
{
公共字符串EmployeeName{get;set;}
public int CategoryId{get;set;}
}
公共类BLL
{
public void SetCategoryId(ICollection已转换,ICollection来源)
{
if(Converted.Count==1&&sourceed.Count==1)
{
if(String.Compare(sourceed.First().EmployeeName,Converted.First().EmployeeName)==0)
{
//将类别id设置为1
Converted.First().CategoryId=1;
sourceed.First().CategoryId=1;
}
其他的
{
//将类别id设置为某个值
}
}
else if(sourceed.Rows.Count==1&&Converted.Rows.Count>1)
{
//将类别id设置为某个值
}
//更多if-else语句。。。
}
}
我认为有一个更好的方法可以做到这一点,也许是通过应用一些设计模式。有什么建议吗?谢谢 是一条路要走
因此,这个对象被传递给一系列命令对象,直到一个人能够操作并设置状态。一个策略模式浮现在脑海中。尝试将这些规则分解为一系列“如果此条件为true,则类别ID为this”。将这些方法中的每一个都设为方法,然后将这些方法作为委托添加到
列表
或类似的索引集合中。然后,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;
}
}
}
public void SetCategoryId(ICollection已转换,ICollection来源)
{
foreach(类别规则中的变量类别规则)
{
var类别=测试(转换、来源);
如果(类别!=0)
{
Converted.First().CategoryId=sourceed.First().CategoryId=category;
打破
}
}
}
无论添加或删除了多少规则,上述代码都不必更改。然而,使用if-else-if结构,您的一系列规则可能会依赖于顺序,因此在列表中设置规则时要小心。设置两个字段的巨大责任链有点过分了,哈哈,但我同意如果他想按照设计模式的方式行事,这是正确的模式。我可以建议在您的答案中添加此链接吗:。这是GOF书籍的参考资料。谢谢大家!为责任链找到了一个很好的C#示例-设置两个字段时,设计模式可能会有些过火……是的,如果我只有两个字段的设计模式,那就太过火了。哈哈。目前大约有12条if-else语句(而且还在增长…。
Strategy/Visitor
不会断开这条链,所以它会一直传递到最后。所以责任链
更好;在找到第一个产生值的策略后,上面的循环现在将爆发。然而,每个策略的执行顺序是至关重要的,完全取决于它们分配给列表的顺序,因此我同意命令链模式在这里会更好。