闪电龟龟--笔记

万物寻其根,通其堵,便能解其困。
  博客园  :: 新随笔  :: 管理

单例的使用

Posted on 2019-09-19 17:01  闪电龟龟  阅读(113)  评论(0编辑  收藏  举报

没有并发的情况下使用单例:

public sealed class Singleton
    {
        private static Singleton l_singleton;
        public static Singleton GetSingleton()
        {
            if(l_singleton==null)
            {
                l_singleton = new Singleton();
            }
            return l_singleton;
        }
    }

有并发的情况下,可以使用下面的单例:

    public sealed class Singleton
    {
        private static Singleton l_singleton;
        private readonly static object l_obj = new object();
        public static Singleton GetSingleton()
        {
            if(l_singleton==null)
            {
                lock(l_obj)
                {
                    if(l_singleton==null)
                    {
                        l_singleton = new Singleton();
                    }
                }
            }
            return l_singleton;
        }
    }