缓存的简单实现例子

来源:互联网 发布:方伯谦 知乎 编辑:程序博客网 时间:2024/05/29 06:41

缓存是软件设计中一个非常有用的模式,缓存的实现方式很多,不同的实现方式可能存在较大的性能差别。

本节使用一个数组来作为缓存池,从而实现一个具有实例缓存的不可变类


public class CacheImmutable

{

   private final String name;

  private static CacheImmutable[] cache=new CacheImmutable[10];

  private static int pos=0;

 

  public CacheImmutable(String name)

{  this.name=name;

}

   public String getName()

{   return name;

}

   public static CacheImmutable valueOf(String name)

{  for(int i=0; i<pos;i++)

  {  

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

     {return cache[i]}


  }

   if(pos==10)

  {  cache[0]=new CacheImmutable(name);

     pos=1;

    return cache[0];

  }

   else

   {  cache[pos++]=new CacheImmutable(name);

     return cache[pos-1];

   }

}

}

}

0 0
原创粉丝点击