簡體   English   中英

選擇設計模式需要幫助

[英]Need help with choosing a design pattern

目前我有一堆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...
    }
}

我認為通過應用一些設計模式可以有更好的方法。 有什么建議? 謝謝!

責任鏈是要走的路。

因此,此對象將傳遞給一系列命令對象,直到一個人能夠對其進行操作並設置狀態。

我想到了一種戰略模式。 嘗試將這些規則分解為一系列“如果這個條件成立,那么類別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結構,您的一系列規則可能與順序有關,因此在列表中設置規則時要小心。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM