修改 Lazy<T> 单例代码

Modification to Lazy<T> singleton code

根据 Jon Skeet 的书籍检查 here 中提供的第 6 个版本创建单例 class。

Class - CacheSingleton

public sealed class CacheSingleton<TK,TV>
    {
        private static readonly Lazy<ICache<TK,TV>> lazyIgnite =
                                                new Lazy<ICache<TK,TV>>(() =>
                                                {
                                                    NearCacheConfiguration nearCacheConfig = new NearCacheConfiguration { NearStartSize = 10240000 };

                                                    var nearCache = IgniteInstance.GetOrCreateNearCache<TK, TV>(SingletonCacheName,nearCacheConfig);

                                                    return nearCache;
                                                });

        /// <summary>
        /// 
        /// </summary>
        private static string SingletonCacheName = string.Empty;

        /// <summary>
        /// 
        /// </summary>
        public static ICache<TK, TV> Instance(string cacheName)
        {
            SingletonCacheName = cacheName;
            return lazyIgnite.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        private CacheSingleton() { }
    }

对原文章的修改:

问题:

任何指向字符串输入中因子的指针,以及 TK,TV

您不能使用 ConcurrentDictionary 来实现吗?类似于:

public static class CacheSingleton<TK, TV>
{
    public static ICache<TK, TV> Instance(string cacheName)
    {
        return _cache.GetOrAdd(cacheName, create);
    }

    static ICache<TK, TV> create(string cacheName)
    {
        // Code to create an ICache<TK, TV> given cacheName.

        return null; // Stubbed.
    }

    static readonly ConcurrentDictionary<string, ICache<TK, TV>> _cache = new ConcurrentDictionary<string, ICache<TK, TV>>();
}

使用 ConcurrentDictionary 怎么样?

public static class CacheSingleton<TK, TV>
{
    private static readonly ConcurrentDictionary<string, ICache<TK, TV>> lazyIgnite = new ConcurrentDictionary<string, ICache<TK, TV>>();

    public static ICache<TK, TV> GetInstance(string cacheName)
    {
        return lazyIgnite.GetOrAdd(cacheName, name =>
        {
            NearCacheConfiguration nearCacheConfig = new NearCacheConfiguration { NearStartSize = 10240000 };
            var nearCache = IgniteInstance.GetOrCreateNearCache<TK, TV>(name, nearCacheConfig);
            return nearCache;
        });
    }
}

这是您的实例的惰性线程安全缓存。 也许您还想实现一个 Clear 方法来重置缓存。