java實(shí)現(xiàn)簡(jiǎn)單的緩存
下面代碼展示用java實(shí)現(xiàn)一個(gè)簡(jiǎn)單緩存:
class CacheImmutable{
private static int MAX_SIZE = 10; //緩存數(shù)量
private static CacheImmutable[] cache //存儲(chǔ)緩存數(shù)據(jù)的數(shù)據(jù)
= new CacheImmutable[MAX_SIZE];
private static int pos = 0;
private final String name;
private CacheImmutable(String name){ //含參構(gòu)造器,結(jié)合上一行final形成不可變
this.name = name;
}
public String getName(){
return name;
}
public static CacheImmutable valueOf(String name){
for (int i = 0; i < MAX_SIZE; i++)
{
if(cache[i] != null && cache[i].getName().equals(name))
{
return cache[i]; //如果緩存中含有該name則直接使用數(shù)組中的name张弛;
}
}
if (pos == MAX_SIZE)
{
cache[0] = new CacheImmutable(name);
pos = 1; //如果緩存數(shù)據(jù)已達(dá)上限扰法,將數(shù)組中第1個(gè)替換痊夭;
}
else
{
cache[pos++] = new CacheImmutable(name);
}
return cache[pos - 1]; //緩存未達(dá)到上限時(shí),正常添加緩存独郎;
}
public boolean equals(Object obj)
{
if(this == obj)
{
return true;
}
if(obj != null && obj.getClass() == CacheImmutable.class)
{
CacheImmutable ci = (CacheImmutable)obj;
return name.equals(ci.getName());
}
return false;
}
public int hashCode()
{
return name.hashCode();
}
}
public class CacheImmutableTest {
public static void main(String[] args)
{
CacheImmutable c1 = CacheImmutable.valueOf("hello");
CacheImmutable c2 = CacheImmutable.valueOf("hello");
System.out.println(c1 == c2);
}
}
上面代碼中,CacheImmutable類直接調(diào)用靜態(tài)方法valueOf(),valueOf()又去調(diào)用含參構(gòu)造器枚赡,既生成CacheImmutable實(shí)例氓癌,又加入了緩存機(jī)制。
實(shí)現(xiàn)的幾個(gè)關(guān)鍵點(diǎn):
1.緩存最大數(shù)量(MAX_SIZE);
2.不可變類(final name贫橙,含參構(gòu)造器直接生成實(shí)例變量顽铸,沒有實(shí)例方法setName());
3.valueOf() 緩存方法中加入3個(gè)場(chǎng)景分支(1.已是緩存的返回邏輯料皇;2.緩存容器已滿谓松,新緩存代替已有緩存的邏輯星压;3.正常加入緩存容器邏輯;)鬼譬,每個(gè)分支都調(diào)用構(gòu)造器生成含有上述邏輯的實(shí)例對(duì)象娜膘;
初學(xué)java,該貼相當(dāng)于學(xué)習(xí)筆記优质,不是到理解的是否有偏差竣贪,希望各位指正,接受并感謝一切有道理的批評(píng)巩螃。