c# - 使用Strategy Design Pattern(C#)对不同列的数据进行排序

标签 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; 
}

然而,这对我来说似乎是一种糟糕的代码味道,它无法轻松添加不同的字段或排序选项,我的导师建议我最好实现策略模式并使用 Dictionary 来选择我们想要的策略实现,但是我不确定策略模式将如何应用于这种情况,任何有用的提示将不胜感激,如果需要更多信息,请询问。

最佳答案

应用策略模式,您将拥有一个ISortStrategy 接口(interface),然后是多个实现,例如SortByIdSortByNameSortByAge 。该接口(interface)及其实现将具有类似 object Sort(Animal animal); 的方法,该方法返回动物的属性之一。

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

return from animal in ctx.Animals
       orderby sortStrategy.Sort(animal) descending
       select animal;

关于c# - 使用Strategy Design Pattern(C#)对不同列的数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20263650/

相关文章:

PHP:将其变成递归函数

java - 在我的构建器模式中找不到匹配的构造函数错误

java - 是否有保证 execute(T t) 方法的内置 Java 类型?

swift - 调用 "strategy design pattern"中的方法时缺少参数标签 -SWIFT

c# - PowerBuilder 调用 C# 代码在某些计算机上崩溃?

javascript - ES7 中新的 async 和 await 关键字是从 C# 复制过来的吗?

c# - 如何快速创建此类子域,例如 Blogger.com

unit-testing - 如何重构和单元测试复杂的遗留 Java EE5 EJB 方法?

java - Strategy Pattern with strategies 包含相似的代码

c# - CS8121 : Custom<T> cannot be handled by a pattern of type 'T'