// 测试
public class CachePoolTest {
public static void main(String[] args) {
CachePool c1 = CachePool.valueOf("cachePool");
CachePool c2 = CachePool.valueOf("cachePool");
System.out.println(c1 == c2);
}
}
// 缓存池
class CachePool {
private static final int MAX_SIZE = 10;
private static CachePool[] pool = new CachePool[MAX_SIZE];
private static int pos = 0; // 游标
private final String name;
private CachePool(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static CachePool valueOf(String name) {
for (CachePool cache : pool) {
if(cache != null && cache.name.equals(name)) {
return cache;
}
}
if(pos == MAX_SIZE) { // 先进先出原则
pool[0] = new CachePool(name);
pos = 1;
} else {
// 等价于赋值pool[pos]后,pos后移1
pool[pos++] = new CachePool(name);
}
return pool[pos-1];
}
}
缓存池-简单实现
最新推荐文章于 2024-05-28 20:50:59 发布