用观察者模式解决点击一次文章 update一次数据库的问题
    
接上文http://xuliangyong.iteye.com/blog/171240
对于第二种方法现用观察着模式来解决
思路是这样:当点击a文章(id=1234)够10次后 ,通知文章管理器更新点击次数
update article set hit_count = hit_count+10 where id = 1234
这样就减少了访问数据库的次数
代码如下:
- publicclassHitCachedextendsObservable{
 
- privatestaticfinalintDEFAULT_MAX_HITS=10;
 
- privateMap<Long,Integer>hits=Collections.synchronizedMap(newHashMap<Long,Integer>());
 
 
 
 
 
- privateintmaxHits=DEFAULT_MAX_HITS;
 
 
- publicHitCached(){}
 
 
- publicHitCached(intmaxHits){
 
- this.maxHits=maxHits;
 
- }
 
 
- publicvoidput(Longkey,Integervalue){
 
- hits.put(key,value);
 
- }
 
 
 
 
 
 
- publicvoidaddHit(Longkey,IntegerhitIncreased){
 
- if(!hits.containsKey(key))
 
- hits.put(key,0);
 
- Integervalue=hits.get(key);
 
- if(value+hitIncreased>=maxHits){
 
- setChanged();
 
- notifyObservers(KeyValuePair.create(key,value+hitIncreased));
 
- hits.remove(key);
 
- }else{
 
- hits.put(key,value+hitIncreased);
 
- }
 
 
- }
 
 
- publicIntegerget(Longkey){
 
- returnhits.get(key);
 
- }
 
 
- publicvoidclear(){
 
- hits.clear();
 
- }
 
 
- }
 
 
- publicclassArticleManagerImplextendsHibernateGenericDao<Article,Long>implementsArticleManag