缓存是软件设计中一个非常有用的模式,缓存的实现方式很多,不同的实现方式可能存在较大的性能差别。
本节使用一个数组来作为缓存池,从而实现一个具有实例缓存的不可变类
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];
}
}
}
}