c# - 实现策略模式而不是几个 if 语句

标签 c# if-statement design-patterns

我有很多if语句的方法,我在其中根据员工职位过滤SharePoint列表。结果是查询字符串 作为参数传递给另一个方法 QuerySPList

 public List<Phone> GetListOfPhones(Employee emp)
 {
    List<Phone> records = new List<Phone>();
    string query = string.Empty;

    if (emp.Positions.Count == 1 && emp.Positions[0] == "Regular")
    {
       query = "";// some querystring                              
    }


    if (emp.Positions.Count == 1 && emp.Positions[0] == "OfficeDirector")
    {   
       query = "";// some querystring    
    }

    if (emp.Positions.Count == 1 && emp.Positions[0] == "Admin")
    {
        query = "";// some querystring 
    }              

    if (emp.Positions.Count == 2 && emp.Positions.Contains("Regular") && emp.Positions.Contains("OfficeDirector"))
    {

      query = "";// some querystring 

     }

   var rawItems = QuerySPList(query);

   foreach (SPListItem item in rawItems)
   {
        //business logic 
   }
   return records;
}}

我读到通过实现strategy pattern我们可以避免带有大量if的困惑代码,但是,我是开发和设计模式的新手,所以我在这方面几乎不需要帮助,所以如果有人可以指导我应该做什么并给我建议,请随时回答我的问题。我有想法,但我认为我走错了方向。 想法是创建 interface IRoleHandler 并将其实现到 3 个 classes ,例如 RoleAdmin ,RoleRegular,RoleOfficeDirector。像这样的事情:

public interface IRoleHandler<T>
{
    string handleRole(T obj);
}
public class RoleAdmin:IRoleHandler<Employee>
{

    public string handleRole(Employee emp)
    {
        if (emp.Positions.Count == 1 && emp.Positions[0] == "Admin")
        {
            //return some string query
        }

    }
}

然后想法是创建字典,像这样:

Dictionary<string, IRoleHandler<Employee>> strategyHandlers = new Dictionary<string, IRoleHandler<Employee>>();
        strategyHandlers.Add("Admin", new RoleAdmin());
        strategyHandlers.Add("Regular", new RoleRegularUser());

最佳答案

首先,我认为您需要较少地关注策略模式的“内部结构”,而更多地关注其设计目标/用途。

https://en.wikipedia.org/wiki/Strategy_pattern

the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm's behavior to be selected at runtime. The strategy pattern

  • defines a family of algorithms,
  • encapsulates each algorithm, and
  • makes the algorithms interchangeable within that family.

在我看来,您实际上是打算根据某些输入值“创建”一个字符串。

因此您可能希望使用 Creational patterns 之一

我的建议可能是工厂模式,或者可能是 builder 模式。 (两者都链接在创建模式链接中)

private string BuildQueryByEmployee(Employee emp) {
    // create your builder
    EmployeeQueryBuilder mBuilder = new EmployeeQueryBuilder ();
    // add # of positions
    mBuilder.addPositionCount(emp.Positions.Count);
    // add each position
    for (int i =0 ; i < emp.Positions.Count; i++ ){
        mBuilder.addPosition(emp.Positions[i]);
    }
    // 'build' your query. 
    // and return the query as a string.
    return mBuilder.buildQuery(); 
}

然后在您的 EmployeeQueryBuilder 类中,您处理如何根据职位数量及其内容构建查询的复杂性。


其次,这里有一些可能对您有用的链接。

  • https://en.wikipedia.org/wiki/Software_design_pattern (模式的一般光盘)
  • https://en.wikipedia.org/wiki/Design_Patterns (《四人帮》这本书,本质上是第一本关于设计模式的书,值得多读几遍,每个模式都要手写几次,直到你熟悉它们,仅此一项就可以将你的编码能力提高 2 ~3x 如果您以前没有使用过模式,本书中的示例有些过时,因为它的激励因素是编写文本编辑器……但仍然是“经典”,非常值得了解)
  • http://www.cs.wustl.edu/~schmidt/POSA/POSA2/ (关于必须处理并发的模式的第一本书籍之一)(POSA = 面向模式的软件架构)(现在可能有点矫枉过正,但总的来说“很好了解”)

关于c# - 实现策略模式而不是几个 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34497348/

相关文章:

c# - 在 .Net 中,在键盘、上键或下键中编写按键代码的更好选择是什么?

c# - 从不同线程读取和写入相同的内存

Java 从多个 session 与数据库进行安全通信

javascript - 如何在 CSS 或 Javascript 中制作曲线形状

if语句中的C++ QList,默认值是多少?

java - OOP 设计 - 需要准备每个方法调用并在之后清理

c# - Visual Studio 2012/Resharper 单元测试不运行

C# DataGridView.DataSource 使用与不使用 BindingSource 的区别

python测试列表中所有项目中的子字符串

java - 在没有变量的 if 语句中验证扫描仪用户输入