订购和过滤数据的设计模式是什么?

mag*_*tic 5 c# design-patterns

我需要在用户通过下拉列表选择的条件之后过滤和排序数据条目.可选择的将是"最新条目优先","最早条目优先","最低价格优先"等.

我可以为选项和switch/case创建一个enum来检索数据,但我宁愿以一种容易扩展的方式来做这件事.

什么设计模式最适合这种情况?

cod*_*ion 5

大家都提到了策略模式。只是想我会发布我的简单实现。没有必要让它变得比必要的更复杂。

public enum SortMethod
{
    Newest,
    Oldest,
    LowestPrice,
}

public class Foo
{
    public DateTime Date {get;set;}
    public decimal Price {get;set;}
}


...
var strategyMap = new Dictionary<SortMethod, Func<IEnumerable<Foo>, IEnumerable<Foo>>>
                  {
                      { SortMethod.Newest, x => x.OrderBy(y => y.Date) },
                      { SortMethod.Oldest, x => x.OrderByDescending(y => y.Date) },
                      { SortMethod.LowestPrice, x => x.OrderBy(y => y.Price) }
                  };

...
var unsorted = new List<Foo>
               {
                   new Foo { Date = new DateTime(2012, 1, 3), Price = 10m },
                   new Foo { Date = new DateTime(2012, 1, 1), Price = 30m },
                   new Foo { Date = new DateTime(2012, 1, 2), Price = 20m }
               };

var sorted = strategyMap[SortMethod.LowestPrice](unsorted);
Run Code Online (Sandbox Code Playgroud)