使用策略设计模式(C#)根据不同的数据列进行排序

Jam*_*nzu 5 c# design-patterns strategy-pattern

我目前正试图了解所有不同的设计模式,我已经设置了IQueryable基于不同列排序的任务,这是当前实现的方式:

if (choice == 1)
{ 
    return from Animals in ctx.Animals orderby Animals.AnimalID descending select Animals; 
}
else if (choice == 2)
{ 
    return from Animals in ctx.Animals orderby Animals.Name descending select Animals; 
}
else if (choice == 3)
{ 
    return from Animals in ctx.Animals orderby Animals.Age descending select Animals; 
}
Run Code Online (Sandbox Code Playgroud)

然而,这似乎是一个糟糕的代码味道,它没有能力轻松添加不同的字段或排序选项,我的导师告诉我,实施策略模式并使用a Dictionary选择策略实现我们会更好但是,我不确定战略模式将如何应用于这种情况,任何有用的提示将非常感激,如果需要更多信息,请问.

dca*_*tro 9

运用策略模式,你就会有一个ISortStrategy接口,然后几个实现比如SortById,SortByName和SortByAge.接口及其实现将有一个object Sort(Animal animal);返回动物属性之一的方法.

然后,您只需在运行时选择正确的策略,并像这样使用它:

return from animal in ctx.Animals
       orderby sortStrategy.Sort(animal) descending
       select animal;
Run Code Online (Sandbox Code Playgroud)

  • @ user2879468是的,你可以做一些像`Dictionary <string,ISortStrategy>`来存储不同的排序策略然后从用户输入查询它,如`ISortStrategy strategy = myDictionary [userInput]` (2认同)