2011-09-09 40 views
1

我有采取不同的输入方法调用,即:构建通用过滤器参数输入接口?

public Authors GetAuthors(string name, string sortBy, string sortDir, int startRow, int numRow) 
{ 
    // Get authors based on filters 
} 

public Books GetBooks(string id, string year, string sortBy, string sorDir, int startRow, int numRow) 
{ 
    // Get books based on filters 
} 

我打算去改变它,这样的过滤器是对象,即:

public Authors GetAuthors(GetAuthorsFilters filters) 
{ 
    // Get authors based on filters 
} 

public Books GetBooks(GetBooksFilters filters) 
{ 
    // Get books based on filters 
} 

但是许多过滤器跨越很常见方法,我想为此构建一个通用接口(即IFilter),它可以接受不同的过滤对象,但不知道从哪里开始。任何建议或建议?

谢谢。

+1

规范模式的完美例证。检查此链接:http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx – Chandu

+0

感谢Cyber​​nate,我会检查链接。 – Saxman

回答

3

在我看来,我会用抽象类来补充你正在寻找的东西。您可以为每种搜索类型创建一个接口,但是每次都必须实现接口,并且看起来BookFilters和AuthorFilters中的共享属性之间没有编程差异。也许像这样:

public abstract class BaseFilter 
{ 
    public string SortBy { get; set; } 
    public bool SortAscending { get; set; } 
    public int RowStart { get; set; } 
    public int RowCount { get; set; } 
} 

public class BookFilter : BaseFilter 
{ 
    public string ISBN { get; set; } 
    public int Year { get; set; } 
} 

public class AuthorFilter : BaseFilter 
{ 
    public string Name { get; set; } 
} 
+1

[匿名用户建议](http://stackoverflow.com/suggested-edits/234938)您使用[ListSortDirection枚举](http://msdn.microsoft.com/en-us/library/system.componentmodel。 listsortdirection.aspx)而不是'bool SortAscending'。 – Rup

3

这听起来像你想在所有的过滤器之间有一些共享的功能。你想要实现这一点的方式不一定是通过接口,而是通过抽象基类。此外,因为您将对不同的对象进行过滤,所以使用泛型是有意义的。你可以有类似以下内容:

public class FilterBase<T> { 
    protected int startRow; 
    ... 

    public FilterBase(Func<T, IComparable> sortBy, bool sortAscending, int startRow, int numRow) { 
     //assigns to member variables 
    } 

    public IEnumerable<T> Filter(IEnumerable<T> toFilter) { 
     filtered = DoFiltering(toFilter); 
     filtered = DoPaging(filtered); 
     filtered = DoSorting(); 
     return filtered; 
    } 

    protected abstract IEnumerable<T> DoFiltering(IEnumerable<T> toFilter); 
    protected virtual IEnumerable<T> DoPaging(IEnumerable<T> toFilter) { 
     return toFilter.Skip(startRow).Take(numRow); 
    } 
    protected virtual IEnumerable<T> DoSorting(IEnumerable<T> toFilter) { 
     return sortAscending ? toFilter.OrderBy(sortBy) : toFilter.OrderByDescending(sortBy); 
    } 
} 

public class BookFilter : FilterBase<Book> { 
    public BookFilter(string id, string year, string sortBy, string sorDir, int startRow, int numRow) : base(sortBy, sorDir, startRow, numRow) { 
     //assign id and year to member variables 
    } 

    protected override IEnumerable<Book> DoFiltering(IEnumerable<Book> toFilter) { 
     return toFilter.Where(b => b.Id == id && b.Year == year); 
    } 
} 

这将让你一次定义分页和排序逻辑为所有类型的过滤器,并具有各类型的定义基于他们的私人自己的自定义过滤成员和他们所指对象的类型。