Object cache implementation

Source: Internet
Author: User

In such a scenario, you need to obtain an instance of a specified interface. First, you need to retrieve it from a cache. If there is one, it will be returned, otherwise, a specified delegate is called to obtain the instance. Suppose there are interfaces and implementations:

    public interface IBar { }    public class Bar : IBar {        public string Name { get; private set; }        public Bar(string name) {            this.Name = name;        }    }    public class TestBar : IBar {     }

 

I want to get the object in some way. If there is a cache (assuming an object of TestBar), I will get it; otherwise, new Bar ("Hello "):

    Cache.Get<IBar>("Hello");

 

My first implementation adopted a Dictionary and cached the Type-> Object + Delegate pair:

    public static class DictCache    {        private class CachedObj        {            public object Instance { get; set; }            public Delegate Callback { get; set; }        }        private static IDictionary<Type, CachedObj> cache = new Dictionary<Type, CachedObj>();        public static T Get<T>(params object[] arguments)        {            CachedObj pair;            if (!cache.TryGetValue(typeof(T), out pair))            {                throw new InvalidOperationException();            }            return (T)(pair.Instance ?? pair.Callback.DynamicInvoke(arguments));        }        public static void Set<T>(object instance, Expression<Func<T>> exp)        {            SetMapping<T>(instance, exp);        }        public static void Set<P, T>(object instance, Expression<Func<P, T>> exp)        {            SetMapping<T>(instance, exp);        }        public static void Set<T>(object instance, LambdaExpression exp)        {            SetMapping<T>(instance, exp);        }        private static void SetMapping<T>(object instance, LambdaExpression exp)        {            cache[typeof(T)] = new CachedObj { Instance = instance, Callback = exp.Compile() };        }    }

 

In this implementation, Delegate is mainly used to delay object creation, and the Set Method is reloaded for convenience.

 

First, we can cache this object:

            DictCache.Set<string, IBar>(new TestBar(), name => new Bar(name));

 

Then use:

            IBar bar = DictCache.Get<IBar>("Hello");

 

Considering that the DynamicInvoke method of Delegate is used in this implementation, there may be Performance problems. My second method uses static classes and uses Delegate as the type parameter:

    public static class StaticCache    {        private static class Cached<T, TDelegate>        {            public static T Instance { get; set; }            public static TDelegate Callback { get; set; }        }        public static T Get<T>() where T : class        {            return (T) (Cached<T, Func<T>>.Instance ?? Cached<T, Func<T>>.Callback());        }        public static T Get<P, T>(P p) where T : class        {            return (T)(Cached<T, Func<P, T>>.Instance ?? Cached<T, Func<P, T>>.Callback(p));        }        public static void Set<T>(T instance, Expression<Func<T>> exp)        {            SetMapping<T, Func<T>>(instance, exp);        }        public static void Set<P, T>(T instance, Expression<Func<P, T>> exp)        {            SetMapping<T, Func<P, T>>(instance, exp);        }        public static void SetMapping<T, TDelegate>(T instance, Expression<TDelegate> exp)        {            Cached<T, TDelegate>.Instance = instance;            Cached<T, TDelegate>.Callback = exp.Compile();        }    }

 

This solution improves the efficiency, but requires more Get and Set reloads for different parameter types and quantities. The usage is as follows:

            StaticCache.Set<string, IBar>(null, name => new Bar(name));

 

Obtain:

            IBar bar = StaticCache.Get<string, IBar>("name");

 

Are there other simpler methods? Make full use of our creativity!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.