您的位置:首页 > 其它

缓存实例的不可变类

2015-04-19 22:58 316 查看
public class CacheImmutale {
//长度
private static int MAX_SIZE=10;
//使用数组缓存实例,最多能缓存10实例
private static CacheImmutale[] cache=new
CacheImmutale[MAX_SIZE];
//记录缓存的位置
private static int pos=0;
//名称
private final String name;
public CacheImmutale(String name)
{
this.name=name;
}
public String getName() {
return name;
}
public static CacheImmutale valueOf(String name)
{
//首先遍历数据中已经缓存的实例对象
for(int i=0;i
{
if(cache[i].getName().equals(name)){
//如果有,就return当前CacheImmutale对象,就不用重新new 了,节省系统资源
return cache[i];
}
}
//如果缓存实例的数组满了,就进行覆盖,将最新的实例放到数组的第一个位置,一边能起一个找到,提升系统性能
if(cache.length==MAX_SIZE){
cache[0]=new CacheImmutale(name);
//设置一下位置
,用作最后的return
pos=1;
}else{
//如果没满
cache[pos++]=new CacheImmutale(name);//cache[pos++]
//弄完后再加加的
}
return cache[pos-1];
}
public boolean equals(Object obj){
if(this==obj)
{
return true;
}
if(obj!=null &&
obj.getClass()==CacheImmutale.class)
{
CacheImmutale cach=(CacheImmutale)obj;
return name.equals(cach.getName());
}
return false;
}
public static void main(String[] args) {
CacheImmutale cacheOne=new CacheImmutale("Test");
CacheImmutale cacheTwo=new CacheImmutale("Test");
//如果返回true,表明系统没有重新创建一个新的实例,而是用缓存中的实例
System.out.println(cacheOne.equals(cacheTwo));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: