Juhász Péter szakmai blogja

The more complex the better

FunctionCache<T, TResult>

leave a comment »

A maximális teljesítmény eléréséhez általában elengedhetetlen a gyorsítótár. Nézzük meg, hogyan lehet ezt megoldani úgy, hogy ne csak a megoldás, hanem a használat is a lehető legegyszerűbb legyen.

/// <summary>
/// Represents a class, that caches the return value of a specified function.
/// </summary>
public class FunctionCache<T, TResult>
{
    /// <summary>
    /// Initializes a new instance of the FunctionCache&lt;T, TResult&gt; class.
    /// </summary>
    /// <param name="func"></param>
    public FunctionCache(Func<T, TResult> func)
    {
        this.Function = func;
        this.Cache = new Dictionary<T, TResult>();
    }

    protected IDictionary<T, TResult> Cache;

    /// <summary>
    /// Gets the function to be cached.
    /// </summary>
    public Func<T, TResult> Function { get; protected set; }

    /// <summary>
    /// Invokes the function and adds its return value to the cache.
    /// </summary>
    /// <param name="arg"></param>
    /// <returns></returns>
    public TResult Invoke(T arg)
    {
        if (!this.Cache.ContainsKey(arg))
            this.Cache.Add(arg, this.Function(arg));

        return this.Cache[arg];
    }

    /// <summary>
    /// Clears cache.
    /// </summary>
    public void Reset()
    {
        this.Cache.Clear();
    }
}

Written by BlueCode

május 18, 2009 at 15:35

Posted in Development

Tagged with ,

Válasz

You must be logged in to post a comment.