Repository模式
近來發(fā)現(xiàn)很多ASP.NET MVC的例子中都使用了Repository模式,比如Oxite,ScottGu最近發(fā)布的免費(fèi)的ASP.NET MVC教程都使用了該模式。就簡單看了下。
在《企業(yè)架構(gòu)模式》中,譯者將Repository翻譯為資源庫。給出如下說明:
通過用來訪問領(lǐng)域?qū)ο蟮囊粋€(gè)類似集合的接口,在領(lǐng)域與數(shù)據(jù)映射層之間進(jìn)行協(xié)調(diào)。
在《領(lǐng)域驅(qū)動(dòng)設(shè)計(jì):軟件核心復(fù)雜性應(yīng)對(duì)之道》中,譯者將Repository翻譯為倉儲(chǔ),給出如下說明:
一種用來封裝存儲(chǔ),讀取和查找行為的機(jī)制,它模擬了一個(gè)對(duì)象集合。
使用該模式的最大好處就是將領(lǐng)域模型從客戶代碼和數(shù)據(jù)映射層之間解耦出來。
我們來看下在LinqToSql中如何應(yīng)用該模式。
1. 我們將對(duì)實(shí)體的公共操作部分,提取為IRepository接口,比如常見的增加,刪除等方法。如下代碼:
1 interface IRepository<T> where T : class 2 { 3 IEnumerable<T> FindAll(Func<T, bool> exp); 4 void Add(T entity); 5 void Delete(T entity); 6 void Save(); 7 }2.下面我們實(shí)現(xiàn)一個(gè)泛型的類來具體實(shí)現(xiàn)上面的接口的方法。
1 public class Repository<T> : IRepository<T> where T : class 2 { 3 public DataContext context; 4 public Repository(DataContext context) 5 { 6 this.context = context; 7 } 8 public IEnumerable<T> FindAll(Func<T, bool> exp) 9 { 10 return context.GetTable<T>().Where(exp); 11 } 12 public void Add(T entity) 13 { 14 context.GetTable<T>().InsertOnSubmit(entity); 15 } 16 public void Delete(T entity) 17 { 18 context.GetTable<T>().DeleteOnSubmit(entity); 19 } 20 public void Save() 21 { 22 context.SubmitChanges(); 23 } 24 }3.上面我們實(shí)現(xiàn)是每個(gè)實(shí)體公共的操作,但是實(shí)際中每個(gè)實(shí)體都有符合自己業(yè)務(wù)的邏輯。我們單獨(dú)定義另外一個(gè)接口,例如:
1 interface IBookRepository : IRepository<Book> 2 { 3 IList<Book> GetAllByBookId(int id); 4 }4.最后該實(shí)體的Repository類實(shí)現(xiàn)如下:
1 public class BookRepository : Repository<Book>, IBookRepository 2 { 3 public BookRepository(DataContext dc) 4 : base(dc) 5 { } 6 public IList<Book> GetAllByBookId(int id) 7 { 8 var listbook = from c in context.GetTable<Book>() 9 where c.BookId == id 10 select c; 11 return listbook.ToList(); 12 } 13 }上面只是為大家提供了一個(gè)最基本使用框架。
作者:生魚片
出處:http://carysun.cnblogs.com/
本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責(zé)任的權(quán)利。
轉(zhuǎn)載于:https://www.cnblogs.com/duanyong/articles/4875798.html
總結(jié)
以上是生活随笔為你收集整理的Repository模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java基础知识强化之IO流笔记42:I
- 下一篇: oracle中的备注的配置与查询