Repository模式定义:
协调领域和数据映射层,利用类似于集合的接口来访问领域对象。
使用此模式最大的好处是将领域模型从客户代码和数据映射层之间解耦出来。
接下来给出一个在Castle ActiveRecord中使用该模式的demo
实体层代码
1: [ActiveRecord("Posts")]
2: public class Post:ActiveRecordBase<Post>
3: {
4: [PrimaryKey("PostId")]
5: public int Id { get; set; }
6:
7: [Property]
8: public string Subject { get; set; }
9:
10: [Property]
11: public string Text { get; set; }
12:
13: [Property]
14: public DateTime DateAdded { get; set; }
15:
16: [BelongsTo("CategoryId")]
17: public Category Category { get; set; }
18:
19: [HasMany(Cascade = ManyRelationCascadeEnum.AllDeleteOrphan, Inverse = true)]
20: public IList<Comment> Comments { get; set; }
21:
22: }
——————————————————分割线————————————————————
1、我们对业务实体持久化操作,提取为IRepository接口
1: public interface IRepository<T> where T:class
2: {
3: T Find(int id);
4: void Add(T entity);
5: void Save(T entity);
6: void Remove(T entity);
7: }
2、对业务实体的私有操作,单独创建一个IPostRepository接口
1: public interface IPostRepository:IRepository<Post>
2: {
3: IEnumerable<Post> FindAll();
4: IEnumerable<Post> FindAll(int index, int count);
5:
6: //IEnumerable<Post> FindAll();
7: //IEnumerable<Post> FindAll(int index, int count);
8: //IEnumerable<Post> FindBy(Query query);
9: //IEnumerable<Post> FindBy(Query query, int index, int count);
10: }
3、实体的Repository类的实现
1: public class PostRepository : IPostRepository
2: {
3: public IEnumerable<Post> FindAll()
4: {
5: return Post.FindAll();
6: }
7:
8: public IEnumerable<Post> FindAll(int index, int count)
9: {
10: return Post.FindAll().Skip(index * count).Take(count);
11: }
12:
13: public Post Find(int id)
14: {
15: return Post.Find(id);
16: }
17:
18: public void Add(Post entity)
19: {
20: entity.Create();
21: }
22:
23: public void Save(Post entity)
24: {
25: entity.Save();
26: }
27:
28: public void Remove(Post entity)
29: {
30: entity.Delete();
31: }
32:
33: }
Respository模式在示例中的实际目的小结一下(来源)
- Repository模式是架构模式,在设计架构时,才有参考价值;
- Repository模式主要是封装数据查询和存储逻辑;
- Repository模式实际用途:更换、升级ORM 引擎,不影响业务逻辑;
- Repository模式能提高测试效率,单元测试时,用Mock对象代替实际的数据库存取,可以成倍地提高测试用例运行速度。
Repository与Dal的区别(来源)
Repository是DDD中的概念,强调Repository是受Domain驱动的,Repository中定义的功能要体现Domain的意图和约束,而Dal更纯粹的就是提供数据访问的功能,并不严格受限于Business层。
使用Repository,隐含着一种意图倾向,就是 Domain需要什么我才提供什么,不该提供的功能就不要提供,一切都是以Domain的需求为核心;而使用Dal,其意图倾向在于我Dal层能使用的数 据库访问操作提供给Business层,你Business要用哪个自己选。换一个Business也可以用我这个Dal,一切是以我Dal能提供什么操 作为核心。
相关文章: