实现仓储模式的最佳方法是什么?

17 浏览
0 Comments

实现仓储模式的最佳方法是什么?

我一直在探索BDD/DDD,并试图找到一个适当的存储库模式的实现方式。目前为止,很难找到一个关于最佳实现方式的共识。我尝试将其归结为以下几种变体,但我不确定哪种方法是最好的。

供参考,我正在构建一个使用NHibernate作为后端的ASP.MVC应用程序。

第一种接口设计:

public interface IRepository {

// 1) 对LINQ的薄包装

T GetById(int id);

void Add(T entity);

void Update(T entity);

void Remove(T entity);

IQueryable Find();

// 或者甚至可能是

T Get(Expression> query);

List Find(Expression> query);

}

第二种接口设计:

public interface IRepository {

// 2) 为每个查询定义自定义方法

T GetById(int id);

void Add(T entity);

void Update(T entity);

void Remove(T entity);

IList FindAll();

IList FindBySku(string sku);

IList FindByName(string name);

IList FindByPrice(decimal price);

// ...以此类推

}

第三种接口设计:

public interface IRepository {

// 3) 在规范模式中封装NHibernate Criteria

void Add(T entity);

void Update(T entity);

void Remove(T entity);

IList FindAll();

IList FindBySpec(ISpecification specification);

T GetById(int id);

}

第四种接口设计:

public interface IRepository {

// 4) 直接暴露NHibernate Criteria

T GetById(int id);

void Add(T entity);

void Update(T entity);

void Remove(T entity);

IList FindAll();

IList Find(ICriteria criteria);

// .. 或者可能是

IList Find(HQL stuff);

}

我的初步想法是:

1) 从效率的角度来看,第一种方法很好,但随着事情变得更加复杂,可能会遇到麻烦。

2) 第二种方法似乎非常繁琐,可能会导致类变得非常拥挤,但在我的领域逻辑和数据层之间提供了高度的分离,我喜欢这一点。

3) 第三种方法在开始时可能比较困难,并且编写查询可能需要更多工作,但它将交叉污染限制在规范层。

4) 这是我最不喜欢的方法,但可能是最直接的实现方式,对于复杂的查询可能是最数据库效率最高的,但它将很多责任放在调用代码上。

0