缓存实例的不可变类
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));
}
}
//长度
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));
}
}
相关文章推荐
- Java_final关键字,不可变类,缓存不可变类实例(缓存池技术)
- 缓存实例的不可变类:
- Java_final关键字,不可变类,缓存不可变类实例(缓存池技术)
- 不可变类和缓存实例的不可变类
- 缓存实例的不可变类
- 缓存不可变类实例的不可变类【参考疯狂Java讲义】
- 疯狂java学习笔记1002---缓存实例的不可变类
- java_数组作缓存池的不可变类实例
- java一个实现实例缓存的不可变类
- 实现一个缓存实例的不可变类
- 缓存实例的不可变类
- 52 Java final 缓存实例的不可变类
- 缓存实例的不可变类
- java 缓存实例的不可变类 p186
- 缓存实例的不可变类:
- 缓存实例的不可变类
- 不可变类的缓存实例
- JAVA中具有实例缓存的不可变类
- JAVA中具有实例缓存的不可变类
- 6.4.8 缓存实例的不可变类