山西坦达清洁设备有限公司

现在的位置: 主页 > 公司荣誉 > 文章列表

文章正文

Asp.Net Design Pattern Studynotes -- Part1

作者:山西坦达清洁设备有限公司 来源:www.sxtdqj.com 发布时间:2017-09-10 09:57:26
Asp.Net Design Pattern Studynotes -- Part1

Asp.Net Design Pattern Studynotes -- Part1

let's start with an exampleto entry amazing OO world !

let's saynow we need to implement a small feature which need :

an entityclass: Product

businesslogic : List<Product>GetProductBy(Function<Product,bool> where);

Service : List<Product> GetProductBy(Function<Product,bool>where);

1st Version

Entity:


[csharp]

public classProduct{}

public classProduct{}

Logic:


[csharp]

public classProductRepositoryV1
{

public List<Product>GetProductBy(Func<Product,bool> where )
{
var products = newList<Product>();
returnproducts.Where(where).ToList();
}
}

public classProductRepositoryV1
{

public List<Product>GetProductBy(Func<Product,bool> where )
{
var products = newList<Product>();
returnproducts.Where(where).ToList();
}
}

service:


[csharp]

classProductServiceV1
{
private ProductRepositoryV1 _productRespository;
private List<Product>_cacheProduct ;

public ProductServiceV1()
{
_productRespository = newProductRepositoryV1(); //1.instant
_cacheProduct = newList<Product>();
}

public List<Product>GetProductListBy(Func<Product,bool> where)
{
var productInCache =_cacheProduct.Where(where);//3.in couple with BL
if (!productInCache.Any())
{
var products =_productRespository.GetProductBy(where);
_cacheProduct.AddRange(products); //2.also care about how to cache
return products;
}
return productInCache.ToList();
}

}

classProductServiceV1
{
private ProductRepositoryV1 _productRespository;
private List<Product>_cacheProduct ;

public ProductServiceV1()
{
_productRespository = newProductRepositoryV1(); //1.instant
_cacheProduct = newList<Product>();
}

public List<Product>GetProductListBy(Func<Product,bool> where)
{
var productInCache =_cacheProduct.Where(where);//3.in couple with BL
if (!productInCache.Any())
{
var products =_productRespository.GetProductBy(where);
_cacheProduct.AddRange(products); //2.also care about how to cache
return products;
}
return productInCache.ToList();
}

}

But we cansee the deficiencies :

For 1stVersion (Original Version):

1.productServiceis in couple with ProductRepository .once productRespository changed method signature, service have to change code.

solution: depend onabstract but not on concrete implementation

2.code is untestable .which need data base ready , but if data base can not connect ,meaning can not be tested.

solution: decoupleservice from business class

3.do multiple things .

a. cache thedata ,b. provice service .c. instance the repository object .

solution : do only one thing .

ok, nowlet's fix it !

2nd version :

Entity: same with above .

business:

[csharp]

企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:襄阳SEO http://xiangyang.4567w.com


COPYRIGHT © 2015 山西坦达清洁设备有限公司 ALL RIGHTS RESERVED.
网站地图 技术支持:肥猫科技
精彩专题:网站建设
购买本站友情链接、项目合作请联系客服QQ:2500-38-100