抽象有助于创建功能,无论是通过基类,接口还是组合,在正确使用时,它们都会为维护,可读性和代码的可重用性带来奇迹。
关于问题中发布的代码,标记为“数据访问层”的代码充当业务层使用的通用抽象。通过这样做,DAL的特定实现(例如示例中的“数据访问SQLServer层”下的内容)与业务层分离。现在,您可以访问不同的数据库,或者是自动送料测试数据DAL等实现
Repository模式是这个工作一个梦幻般的例子在DAL(例如简化):
public interface IProductRepository
{
Product Get(int id);
...
}
public class SqlProductRepository : IProductRepository
{
public Product Get(int id) { ... }
...
}
public class MockProductRepository : IProductRepository
{
private IDictionary<int, Product> _products = new Dictionary<int, Product>()
{
{ 1, new Product() { Name = "MyItem" } }
};
public Product Get(int id) { return _products[id]; }
...
}
public class AwesomeBusinessLogic
{
private IProductRepository _repository;
public AwesomeBusinessLogic(IProductRepository repository)
{
_repository = repository;
}
public Product GetOneProduct()
{
return _repository.GetProduct(1);
}
}
即使此示例使用接口,同样适用于使用基类。美丽的是,现在我可以喂SqlProductRepository
或MockProductRepository
到AwesomeBusinessLogic
和不必改变任何关于AwesomeBusinessLogic
。如果出现其他情况,所需的全部是IProductRepository
和AwesomeBusinessLogic
的新实现将仍然处理它,因为它只通过接口访问存储库。
我的问题是改进的。对吧?需要投票重新打开它.... – Pankaj 2012-03-14 13:13:27
我没有投票结束它之前。 – Tigran 2012-03-14 13:21:46
当你说“backcompatibility怎么样?”时无法理解。你能让它更精确吗? – Pankaj 2012-03-14 13:28:17