Examples of the use of a single

Without concurrent use of a single case:

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

Under circumstances there is concurrent, the following may be used alone Example:

    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;
        }
    }

 

Guess you like

Origin www.cnblogs.com/namejr/p/11537764.html