|
using System;
using System.Collections.Generic;
namespace Light.Model
{
/// <summary>
/// Cache used by Dao objects.
/// </summary>
public class LRUCache<T>
{
private Dictionary<string, LinkedListNode<T>> dict;
private LinkedList<T> list;
private int size = 0;
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="sz">maximum number of objects to store</param>
public LRUCache(int sz)
{
size = sz < 10 ? 10 : sz;
dict = new Dictionary<string, LinkedListNode<T>>(size);
list = new LinkedList<T>();
}
/// <summary>
/// Gets or sets the maximum number of objects to store.
/// </summary>
public int Size
{
get { return size; }
set { size = value < 10 ? 10 : value; }
}
/// <summary>
/// Stores the given object. Overwrites if key exists.
/// </summary>
/// <param name="key">key under which to store given object</param>
/// <param name="item">object to store</param>
public void Put(string key, T item)
{
LinkedListNode<T> node;
if(dict.TryGetValue(key, out node))
{
list.Remove(node);
node = new LinkedListNode<T>(item);
dict[key] = node;
list.AddFirst(node);
}
else
{
if(list.Count == size)
list.RemoveLast();
node = new LinkedListNode<T>(item);
dict[key] = node;
list.AddFirst(node);
}
}
/// <summary>
/// Returns an object associated with given key.
/// </summary>
/// <param name="key">key under which an object was previously stored</param>
/// <returns>object or null if key is not found</returns>
public T Get(string key)
{
LinkedListNode<T> node;
if(dict.TryGetValue(key, out node))
{
list.Remove(node);
list.AddFirst(node);
return node.Value;
}
return default(T);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.