Java 中缓存机制的实现

来源:互联网 发布:温州淘宝运营培训 编辑:程序博客网 时间:2024/05/16 07:28

转载地址: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
原创粉丝点击