2011-07-21 23 views
0

沒有感覺說得對數據訪問設計當我開始我有一個接口:使用許多方法

public interface IBlogReader 
{ 
    BlogPost GetLatest(); 
    IEnumerable<BlogPost> FindByDate(DateTime from, int limit); 
    IEnumerable<BlogPost> FindByCategory(string category, int limit); 
    IEnumerable<BlogPost> FindByAuthor(string author, int limit); 
} 

然後我需要查詢的不同排列(FindByAuthorWithCategory,FindByDateWithAuthor等),我想我需要改變這種方法會繼續增長。我需要更多不同的查詢。接下來我有一個接口,如:

public struct FindCriteria 
{ 
    DateTime? from; 
    string category; 
    string author; 
} 

public interface IBlogReader 
{ 
    BlogPost GetLatest(); 
    IEnumerable<BlogPost> Find(FindCriteria criteria); 
} 

接口更小,我可以避免做出許多方法。但是,我基本上將許多方法實現移到了一個大聲的單一方法實現中。這讓我感覺好一陣子了。我想移動到了一種方法,包裹的大乎乎的查詢方法爲一系列其中每個對象處理的具體單個對象的,我呼籲的結果:

public abstract class QueryCommand 
{ 
    protected IBlogReader reader = null; 
    public QueryCommand(IBlogReader reader) 
    { 
     this.reader = reader; 
    } 

    public abstract void Execute(); 
} 

public class GetLatest : QueryCommand 
{ 
    public BlogPost GetResults(); 
    public void Execute(); 
} 

public class FindByDate : QueryCommand 
{ 
    public IEnumerable<BlogPost> GetResults(); 
    public void Execute(); 
} 

它仍然感覺不對。我讀到了Repository模式,我不明白它是如何應用的。在我看來,我最終還是會得到許多方法。數據正在存儲在雲中。使用規範模式的權重太重了,因爲我閱讀它會把所有的記錄帶到本地。在另一個嘗試中,我創建了單獨的DAO對象,並將它們包裝在類庫之類的外觀對象中。最終的結果與我用......許多方法開始的結果是一樣的......但是存儲庫並沒有完成所有的工作。

我是否應該解決自己有多種方法或許多對象並克服它?

回答

0

看起來像Query Object。 有時我們也使用它的變化:

public class Filter 
{ 
    public DateTime? PostDate { get; set; } 
    public DateTime? LastComment { get; set; } 
    public string Author { get; set; } 
} 

然後解決非空的標準來篩選表達。

+0

是的,但在我看來好像干擾所有的方法到一個單一的方法。當然,過濾器包含所有的參數,但邏輯仍然會在某個地方。在我看來,除了代碼的位置以外沒有真正的區別。 –

+0

是的,擺脫此代碼的唯一方法是使用一些包含它的庫。例如,讓我們想象一下基於屬性構建它的庫。恐怕沒有代碼就沒有辦法做到這一點。 – artplastika

0

你爲什麼不公開一個IQueryable<BlogPost>?你描述的問題正是爲什麼這種方法有意義。

這裏是你的界面,修改:

public interface IBlogReader 
{ 
    IQueryable<BlogPost> Posts { get; } 
} 

然後,你可以只執行查詢:

IBlogReader myReader = new MyReader(); 
var latest = myReader.Posts.Last(); 
var posts = myReader.Posts.Where(x => x.Author == "John Smith"); 

等。

請注意,已經有一些數據訪問解決方案支持這種應用,比如LINQ to SQL,Entity Framework或NHibernate。