抽象有助於創建功能,無論是通過基類,接口還是組合,在正確使用時,它們都會爲維護,可讀性和代碼的可重用性帶來奇蹟。
關於問題中發佈的代碼,標記爲「數據訪問層」的代碼充當業務層使用的通用抽象。通過這樣做,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