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:

public classProduct{}

Logic:

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

service:

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:

interface IProductRespository//added interface fordependency inversion
{
List<Product>GetProductBy(Func<Product, bool> where);
}
class ProductRespositoryV2:IProductRespository
{
public List<Product>GetProductBy(Func<Product, bool> where)
{
var products = newList<Product>();
returnproducts.Where(where).ToList();
}
}

Service :

class ProductServiceV2
{
private IProductRespository _productRespository;
private List<Product>_cacheProduct ; public ProductServiceV2(IProductRespositorypr)
{
_productRespository = pr;
_cacheProduct = newList<Product>();
} public List<Product> GetProductListBy(Func<Product,bool> where)
{
var productInCache =_cacheProduct.Where(where);
if (!productInCache.Any())
{
var products =_productRespository.GetProductBy(where);
_cacheProduct.AddRange(products);
return products;
}
return productInCache.ToList();
}
}

For 2ndVersion (Applydependency inversion + Dependency injection):

.still do multiple things:

a.still need to care about how to store . b. provide service

solution :put the responsibility of cache storage into another class,let service only depends on interface (IStorage)

3rd Version(Adapter pattern + Dependency inversion)

Entity :same with above .

business:

interface IProductRespository
{
List<Product> GetProductBy(Func<Product, bool> where);
}
interface IStorage
{
void Add(IEnumerable<Product>products);
IEnumerable<Product> Get(Func<Product, bool> where);
} class MemoryStorage:IStorage // Take the responsibility ofCache
{
private List<Product>_cacheProduct;
public MemoryStorage()
{
_cacheProduct = newList<Product>();
}
public void Add(IEnumerable<Product> products)
{
_cacheProduct.AddRange(products);
} public IEnumerable<Product> Get(Func<Product, bool> where)
{
return _cacheProduct.Where(where);
}
} class ProductRespositoryV3:IProductRespository
{
public List<Product> GetProductBy(Func<Product, bool> where)
{
var products = new List<Product>();
return products.Where(where).ToList();
}
}

Service:

class ProductServiceV3
{
// only dependson abstract
private IProductRespository_productRespository;
private IStorage_cache; public ProductServiceV3(IProductRespository pr, IStorage storage)
{
//new objalso do not care
_productRespository = pr;
_cache = storage;
}
public List<Product> GetProductListBy(Func<Product,bool> where)
{
var productInCache = _cache.Get(where);
if (!productInCache.Any())
{
var products = _productRespository.GetProductBy(where);
_cache.Add(products);
return products;
}
return productInCache.ToList();
}
}

We Can see ,

1.Service only depends on Interface which is abstract(no more need to care about how to cache the data) ,

2.and for Service, storage and respository class only do one thing

3.for service ,respository ,storage all can be UT .

Whenever weare coding any class,always remember these 3 things :

1.only do one thing

2.depends only on abstract

3.always can be tested

Asp.Net Design Pattern Studynotes -- Part1的更多相关文章

  1. Thinking In Design Pattern——MVP模式演绎

    原文<Thinking In Design Pattern——MVP模式演绎>不知为何丢失了,故重新整理了一遍. 目录 What Is MVP Domain Model StubRepos ...

  2. 说说设计模式~大话目录(Design Pattern)

    回到占占推荐博客索引 设计模式(Design pattern)与其它知识不同,它没有华丽的外表,没有吸引人的工具去实现,它是一种心法,一种内功,如果你希望在软件开发领域有一种新的突破,一个质的飞越,那 ...

  3. 设计模式(Design Pattern)系列之.NET专题

    最近,不是特别忙,重新翻了下设计模式,特地在此记录一下.会不定期更新本系列专题文章. 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结. 使用 ...

  4. [转]Design Pattern Interview Questions - Part 4

    Bridge Pattern, Composite Pattern, Decorator Pattern, Facade Pattern, COR Pattern, Proxy Pattern, te ...

  5. [转]Design Pattern Interview Questions - Part 2

    Interpeter , Iterator , Mediator , Memento and Observer design patterns. (I) what is Interpreter pat ...

  6. [转]Design Pattern Interview Questions - Part 3

    State, Stratergy, Visitor Adapter and fly weight design pattern from interview perspective. (I) Can ...

  7. [转]Design Pattern Interview Questions - Part 1

    Factory, Abstract factory, prototype pattern (B) What are design patterns? (A) Can you explain facto ...

  8. design pattern

    1. visitor design pattern http://butunclebob.com/ArticleS.UncleBob.IuseVisitor

  9. Design Pattern: Observer Pattern

    1. Brief 一直对Observer Pattern和Pub/Sub Pattern有所混淆,下面打算通过这两篇Blog来梳理这两种模式.若有纰漏请大家指正. 2. Use Case 首先我们来面 ...

随机推荐

  1. jQuery学习 day01

    最近受某大牛指点(我不会说他姓范),了解了一下jQuery,据说很牛X,就了解了一下,第一天,分享给大家一些心得吧. 1.首先就是导入jQuery文件了,这里我是去jQuery官网下载的.(大家可以去 ...

  2. javascript 学习笔记之模块化编程

    题外: 进行web开发3年多了,javascript(后称js)用的也比较多,但是大部分都局限于函数的层次,有些公共的js函数可重用性不好,造成了程序的大量冗余,可读性差(虽然一直保留着注释的习惯,但 ...

  3. Lucene4.9学习笔记——Lucene建立索引

    基本上创建索引需要三个步骤: 1.创建索引库IndexWriter对象 2.根据文件创建文档Document 3.向索引库中写入文档内容 这其中主要涉及到了IndexWriter(索引的核心组件,用于 ...

  4. iOS开发之自定义控制器切换

    iOS8以后, 苹果公司推出了UIPresentationController, 通过其(presentedController 和 presentingController)来控制modal控制器操 ...

  5. scanf格式控制符

    格式控制 . %d %o %x %c %s %f %e 无%u格式.%g格式 . scanf("%3d%3d", &a, &b); 输入: //a=123,b=45 ...

  6. nutch2.2.1

    http://blog.csdn.net/leave00608/article/details/17442163 https://svn.apache.org/repos/asf/nutch/tags ...

  7. mysql connect

    def connect(_host, _user, _passwd, _db, _charset, _port): conn = MySQLdb.connect(host=_host, user=_u ...

  8. php 文件下载 以及 file_exists找不到文件的解决方案

    链接:<a href="upload/file/download.php?filename=雨人工作室.doc" target="_blank" > ...

  9. decode_json 必须是unicode形式的字符

    centos6.5:/root/test#cat a1.pl use JSON qw/encode_json decode_json/; use Encode; my $data = [ { 'nam ...

  10. Beta Round #9 (酱油杯noi考后欢乐赛)PLQ和他的小伙伴们

    题目:http://www.contesthunter.org/contest/Beta%20Round%20%EF%BC%839%20%28%E9%85%B1%E6%B2%B9%E6%9D%AFno ...