我希望在一个小项目中使用 IRepository 模式(如果重要的话,由 NHibernate 支持)。该域是一个简单的域,故意这样让我能够专注于理解 IRepository 模式。唯一的域类是Movie
,其属性为Year
, Genre
, and Title
。我的目的是“获得”其属性符合上述类型标准的电影。
约定似乎有一个通用的IRepository
界面,类似如下:
public interface IRepository<T>
{
T Get(int id);
T[] GetAll();
void Add(T item);
void Update(T item);
void Delete(T item);
}
通过基本实现:
public abstract class Repository<T> : IRepository<T>
{
public T Get(int id) { ... }
public T[] GetAll() { ... }
public void Add(T item) { ... }
public void Update(T item) { ... }
public void Delete(T item) { ... }
}
然后有一个特定于域的接口:
public interface IMovieRepository
{
Movie[] GetByGenre(Genre genre);
Movie[] GetByYear(int year);
Movie[] GetByTitle(string title);
}
通过还扩展基础的实现Repository
class:
public class MovieRepository : Repository<Movie>, IMovieRepository
{
public Movie[] GetByGenre(Genre genre) { ... }
public Movie[] GetByYear(int year) { ... }
public Movie[] GetByTitle(string title) { ... }
}
我需要使用 NHibernate 向基类和具体类添加必要的实现,但我想知道我的设置是否正确。
仅一个域类似乎会产生相当大的开销,但如果涉及多个域类,开销就不那么明显了。现在我试图保持简单,这样我就可以确定这个概念。