Java 中缓存机制的实现

转载地址:http://blog.sina.com.cn/s/blog_6b2ef10601017fch.html

所谓缓存,就是将程序或系统经常要调用的对象存在内存中,一遍其使用时可以快速调用,不必再去创建新的重复的实例。这样做可以减少系统开销,提高系统效率。缓存机制的实现有很多中,这里讲一种。

 

 

public class CacheImmutale{

    //声明要缓存的类名;

    private final String className;

         //声明10个缓存池

         private static CacheImmutale[] cache= new CachImmutale[10];

         //记录缓存的位置,最新位置为[pos-1]

         private static int pos=0;

         //构造器

         public CacheImmutale(String className){

             this.className=className;

         }

         //返回方法

         public String getName(){

             return className;

         }

         //返回对象实例名,传进要使用的实例名,由该方法去判断缓存池中是否存在

         public static CacheImmutale valueOf(String className){

             //遍历缓存池,若存在,返回

             for(int i=0;i

                       if(cache[i]!=null&&cache[i].getName().equals(className)){

                                return cache[i];

                            }

                           

                   }

                   //如果缓存池满,则采取先进先出

                   if(pos==10){

                       cache[0]=new CacheImmutale(className);

                            pos=1;

                            return cache[0];

                   }

                   else{

                       cache[pos++]=new CacheImmutale(className);

                            return cache[pos-1];

                   }

         }

         public boolean equals(Object obj){

             if(obj instanceof CacheImmutale){

                       CacheImmutale c1=(CacheImmutale)obj;

                            if(className.equals(c1.getName())){

                                return true;

                            }

                   }

                   return false;

         }

         public int hashCode(){

             return className.hashCode();

         }

        

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值