我正在创建一个示例应用程序来一起理解存储库和工厂方法模式,因为将在更大的项目中使用。
我想要实现的是能够使网站与不同的 ORM 工具一起使用。
例如,网站将实现 LINQ to SQL 和 Ado Entity Framework 工作类,然后使用工厂方法将使用这些 ORM 之一“使用配置值”来加载存储库对象中的数据。
到目前为止我得到的内容如下
interface IRepository : IDisposable
{
IQueryable GetAll();
}
interface ICustomer : IRepository
{
}
public class CustomerLINQRepository : ICustomer
{
public IQueryable GetAll()
{
// get all implementation using linqToSql
}
public void Dispose()
{
throw;
}
public IRepository GetObject()
{
return this;
}
}
public class CustomerADORepository : ICustomer
{
public IQueryable GetAll()
{
// get all implementation using ADO
}
public void Dispose()
{
throw new NotImplementedException();
}
public IRepository GetObject()
{
return this;
}
}
// Filling a grid with data in a page
IRepository customers = GetCustomerObject();
this.GridView1.DataSource = customers.GetAll();
this.GridView1.DataBind();
////
public IRepository GetCustomerObject()
{
return new CustomerLINQRepository(); // this will return object based on a config value later
}
但是我感觉有很多设计错误希望你能帮我解决,以获得更好的设计。
最佳答案
我的两分钱:
A.我会添加通用基础存储库类。无论类型是什么,许多存储库操作都是相同的。它可以节省您大量的打字时间。
B.我不明白为什么您的存储库要实现 ICustomer 接口(interface)。 数据对象的接口(interface)是一个很好的实践,但我认为您的存储库不应该实现它。
C.如果您的数据对象有一个通用的实现,我将为它们创建一个基类,并将存储库限制为仅适用于该类型的派生类。
我会做类似的事情:
public interface IEntity
{
// Common to all Data Objects
}
public interface ICustomer : IEntity
{
// Specific data for a customer
}
public interface IRepository<T, TID> : IDisposable where T : IEntity
{
T Get(TID key);
IList<T> GetAll();
void Save (T entity);
T Update (T entity);
// Common data will be added here
}
public class Repository<T, TID> : IRepository<T, TID>
{
// Implementation of the generic repository
}
public interface ICustomerRepository
{
// Specific operations for the customers repository
}
public class CustomerRepository : Repository<ICustomer, int>, ICustomerRepository
{
// Implementation of the specific customers repository
}
用法:
CustomerRepository repository = new CustomerRepository();
IList<ICustomer> customers = repository.GetAll();
// Do whatever you want with the list of customers
这就是我使用 NHibernate 实现 DAL 的方式。您可以在“NHibernate in Action”中找到该用法的一些变化。
我还建议按照 Matt 的建议使用某种 IoC Controller 。
关于c# - 如何使用存储库模式和工厂方法模式组织我的类/接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1490436/