在选择设计模式方面需要帮助
目前,我有一堆 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...
}
}
我认为有更好的方法可以通过应用一些设计模式来做到这一点。有什么建议吗?谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
责任链是正确的选择。
因此,该对象被传递给一系列命令对象,直到能够执行操作并设置状态为止。
Chain of responsibility is the way to go.
So this object is passed to a series of command objects until one is able to act upon and set the status.
我想到了一种策略模式。尝试将这些规则分解为一系列“如果这个条件为真,那么类别ID就是这个”。将其中每一个方法设为方法,然后将这些方法作为委托添加到
List、ICollection、bool>>
或类似的索引集合。然后,您的 SetCategoryId() 代码如下所示:无论您添加或删除多少规则,上述代码都无需更改。但是,使用 if - else if 结构,您的一系列规则可能会依赖于顺序,因此在列表中设置规则时要小心。
A Strategy pattern comes to mind. Try to break these rules down into a series of "if this condition is true, then the category ID is this". Make each one of these a method, then add those methods as delegates to a
List<Func<ICollection<TeamWork>, ICollection<TeamWork>, bool>>
or a comparable indexed collection. Then, your SetCategoryId() code looks like this:The above code would never have to change regardless of how many rules you added or removed. However, with the if - else if structure you have, your series of rules will likely be order-dependent, so be careful when setting up the rules in the list.