美文网首页
2018-04-11

2018-04-11

作者: 抓虫的蜗牛 | 来源:发表于2018-04-11 17:30 被阅读0次

    java实现简单的缓存

    下面代码展示用java实现一个简单缓存:

    
    class CacheImmutable{
        private static int MAX_SIZE = 10;  //缓存数量
        private static CacheImmutable[] cache  //存储缓存数据的数据
            = new CacheImmutable[MAX_SIZE];
        private static int pos = 0;
        private final String name;   
        private CacheImmutable(String name){   //含参构造器,结合上一行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则直接使用数组中的name;
                }
            }
            if (pos == MAX_SIZE)
            {
                cache[0] = new CacheImmutable(name);
                pos = 1;   //如果缓存数据已达上限,将数组中第1个替换;
            }
            else
            {
                cache[pos++] = new CacheImmutable(name);
            }
            return cache[pos - 1]; //缓存未达到上限时,正常添加缓存;
        }
        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类直接调用静态方法valueOf(),valueOf()又去调用含参构造器,既生成CacheImmutable实例,又加入了缓存机制。
    实现的几个关键点:
    1.缓存最大数量(MAX_SIZE);
    2.不可变类(final name,含参构造器直接生成实例变量,没有实例方法setName());
    3.valueOf() 缓存方法中加入3个场景分支(1.已是缓存的返回逻辑;2.缓存容器已满,新缓存代替已有缓存的逻辑;3.正常加入缓存容器逻辑;),每个分支都调用构造器生成含有上述逻辑的实例对象;

    初学java,该贴相当于学习笔记,不是到理解的是否有偏差,希望各位指正,接受并感谢一切有道理的批评。

    相关文章

      网友评论

          本文标题:2018-04-11

          本文链接:https://www.haomeiwen.com/subject/vnezhftx.html