缓存实例的不可变类

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));
}
}

转载于:https://my.oschina.net/yangrunkang/blog/677542

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值