用數組來實現作爲緩存池,從而實現一個緩存實例的不可變類
在public class CacheImmutale {
private static int MAX_SIZE=10;
//使用數組來緩存已有的實例
private static CacheImmutale[]cache=new CacheImmutale[MAX_SIZE];
//記錄緩存實例在緩存中的位置,cache[pos-1]是最新緩存的實例
private static int pos=0;
private final String name;
private CacheImmutale(String name) {
this.name=name;
}
public String getName() {
return name;
}
public static CacheImmutale Value(String name) {
//遍歷已緩存的對象
for(int i=0;i<MAX_SIZE;i++) {
//如果已有相同實例,則直接返回該緩存的實例
if(cache[i]!=null && cache[i].getName().equals(name)){
return cache[i];
}
}
//如果緩存池已滿
if(pos==MAX_SIZE) {
//把緩存的第一個對象覆蓋,即把剛剛生成的對象放在緩存池的最開始位置
cache[0]=new CacheImmutale(name);
//把pos設爲1
pos=1;
}
else
{
//把新創建的對象緩存起來,pos加1
cache[pos++]=new CacheImmutale(name);
}
return cache[pos-1];
}
public boolean equals(Object obj) {
if(this==obj)
{
return true;
}
if(obj!=null&&obj.getClass()==CacheImmutale.class) {
CacheImmutale ci=(CacheImmutale)obj;
return name.equals(ci.getName());
}
return false;
}
public int hasCode() {
return name.hashCode();
}
}
public class CacheImmutaleTest {
public static void main(String[]args) {
CacheImmutale c1=CacheImmutale.valueOf("hello");
CacheImmutale c2=CacheImmutale.valueOf("hello");
//下面代碼將輸出true
System.out.println(c1==c2);
}
}