LRUCache是Least Recently Used 近期最少使用算法的缓存,是android提供的一个缓存工具类。可以以两种排序方式来输出缓存,一种是按插入顺序输出,一种是按最近最少方式输出,最近使用的放在队首,使用频率低的,间隔时间最长的放在队尾。
下面是实现

using System;
using System.Collections.Generic;
namespace LY.Helper
{
public class LRUCache<T>
{
private Dictionary<string, T> dict;
private LinkedList<T> list;
private int size = ;
private bool isSequence = false; public LRUCache(int sz):this(sz,false)
{ } public LRUCache(int sz, bool isSq)
{
isSequence = isSq;
size = sz < ? : sz;
dict = new Dictionary<string, T>(size);
list = new LinkedList<T>();
} public int Size
{
get { return size; }
set { size = value < ? : value; }
} public void Put(string key, T item)
{
T node;
if(dict.TryGetValue(key, out node))
{
list.Remove(node); dict[key] = item;
list.AddFirst(item);
}
else
{
if(list.Count == size)
list.RemoveLast();
dict[key] = item;
list.AddFirst(item);
}
} public T Get(string key)
{
T node;
if(dict.TryGetValue(key, out node))
{
list.Remove(node);
list.AddFirst(node);
return node;
}
return default(T);
} public ICollection<T> Values
{
get
{
if (isSequence)
{
return dict.Values;
}
else
{
return list;
}
}
}
}
}

构造函数中传入缓存大小和输出缓存顺序。
我们在调用Put方法时,当缓存长度超过我们构造函数中传入的大小时,会将队尾的移除。将新传入的对象放在队首。
我们从LRUCache中获取对象时,在Get方法中,会将对象移除,并置于队首。
下面我们来进行测试

private void btnTest_Click(object sender, EventArgs e)
{
LRUCache<int> lruCache = new LRUCache<int>();
lruCache.Put("", );
lruCache.Put("", );
lruCache.Put("", );
lruCache.Put("", );
lruCache.Put("", );
lruCache.Get("");
lruCache.Get(""); Console.WriteLine("最近最少方式Test...");
foreach (var item in lruCache.Values)
{
Console.WriteLine(item.ToString());
} LRUCache<int> lruCache1 = new LRUCache<int>(, true);
lruCache1.Put("", );
lruCache1.Put("", );
lruCache1.Put("", );
lruCache1.Put("", );
lruCache1.Put("", ); lruCache1.Get("");
lruCache1.Get(""); Console.WriteLine("顺序方式Test...");
foreach (var item in lruCache1.Values)
{
Console.WriteLine(item.ToString());
}
}

我们来看下输出结果

 
LRUCache c#-LMLPHP
04-17 03:57