日期:2014-05-16  浏览次数:20523 次

用观察者模式解决点击一次文章 update一次数据库的问题

接上文http://xuliangyong.iteye.com/blog/171240

对于第二种方法现用观察着模式来解决

思路是这样:当点击a文章(id=1234)够10次后 ,通知文章管理器更新点击次数

update article set hit_count = hit_count+10 where id = 1234

这样就减少了访问数据库的次数

代码如下:

Java代码
  1. publicclassHitCachedextendsObservable{
  2. privatestaticfinalintDEFAULT_MAX_HITS=10;
  3. privateMap<Long,Integer>hits=Collections.synchronizedMap(newHashMap<Long,Integer>());
  4. /**
  5. *最大点击量。超过该值就更新数据库
  6. */
  7. privateintmaxHits=DEFAULT_MAX_HITS;
  8. publicHitCached(){}
  9. publicHitCached(intmaxHits){
  10. this.maxHits=maxHits;
  11. }
  12. publicvoidput(Longkey,Integervalue){
  13. hits.put(key,value);
  14. }
  15. /**
  16. *为指定key增加指定的点击量
  17. *@paramhitIncreased增加的点数
  18. */
  19. publicvoidaddHit(Longkey,IntegerhitIncreased){
  20. if(!hits.containsKey(key))
  21. hits.put(key,0);
  22. Integervalue=hits.get(key);
  23. if(value+hitIncreased>=maxHits){
  24. setChanged();
  25. notifyObservers(KeyValuePair.create(key,value+hitIncreased));
  26. hits.remove(key);
  27. }else{
  28. hits.put(key,value+hitIncreased);
  29. }
  30. }
  31. publicIntegerget(Longkey){
  32. returnhits.get(key);
  33. }
  34. publicvoidclear(){
  35. hits.clear();
  36. }
  37. }
Java代码
  1. publicclassArticleManagerImplextendsHibernateGenericDao<Article,Long>implementsArticleManag