Head First Design Patterns - singleton

Singleton design pattern is all in the simplest model, which we usually often used, Singleton pattern is often used in our thread pool, cache operations, queue operations, and so on.

Singleton aims to create an instance of a class, create an instance of a class, we use the global static variable or the agreement can do the role of a single example of why we use the Singleton pattern?

Next we went from how to form a single-case model, the process of creation of the Singleton pattern to explain.

1, how to form a singleton

We usually create an object needs new objects, if there is an object ObjectClass we instantiate it.

new ObjectClass()

If you want to use another class ObjectClass you can re-create another instance of, if the class is public then we can instantiate an object many times when in use by the new.

Then how do we ensure that classes are not instances of other classes, using the private key that we can use a private constructor to prevent external instantiate the class.

public class ObjectClass
{
   private ObjectClass()
    {
    }    
}

As a result we can not be instantiated ObjectClass then we can not use it. That how we want to instantiate it?

Since we can only access the private constructor inside, so we can use an internal method of the ObjectClass instance, in order to access external This method will be set to this method of static.

After this is done to ensure that the returned object is always the object is first created, we use a private static object to store instantiated object, if the object did not create us to create immediately, if it has been created to return the object has been created.

    public class ObjectClass
    {
        private static ObjectClass singleton;
        private ObjectClass()
        {
        }

        public static ObjectClass GetSingletone()
        {
            if (singleton == null)
            {
                singleton = new ObjectClass();
            }
            return singleton;
        }
    }

Here we single embodiment mode is formed, a single schema definition Example:

Singleton: ensure that only one instance of a class, and provide a global access point.

2, multi-threaded lead singleton problem

Enabling multi-threaded test returns a singleton objects

    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                TestSingleton ();
            }
            Console.ReadKey();
        }

        public static void TestSingleton()
        {
            Task.Factory.StartNew(new Action(() =>
            {
                var hc = ObjectClass.GetSingletone().GetHashCode();
                Console.WriteLine(hc);
            }));
        }
    }

  

As shown in tests done, I start 10 threads get singleton object and then print the object HashCode. Testing found inconsistencies HashCode, the object of proof is not a single example returns only one.

Because the multi-threaded operation may simultaneously enter if (singleton == null) to determine if this time variable is not yet instantiated singleton may have a plurality of threads into instantiation code, object instances that are not returned the same one.

3, to solve the problem of multi-thread Singleton

Because multi-threaded lead to problems if inspect variables, the fight to check for problems we can have two types of solutions:

① "eager" to create an instance, do not delay instantiation practice

Eager instantiation is to create objects in a static initializer, thus ensuring the operational phase of the program singleton object has been created, the removal if the judge.

    public class ObjectClass
    {
        private static ObjectClass singleton=new ObjectClass();
        private ObjectClass()
        {
        }

        public static  ObjectClass GetSingletone()
        {
            return singleton;
        }
    }

lock

In order to create an object only one thread operation, we lock processing for creating object code, reform GetSingletone method again.

    public class ObjectClass
    {
        private static ObjectClass singleton = new ObjectClass();
        private static object lockObj = new object();
        private ObjectClass()
        {
        }

        public static ObjectClass GetSingletone()
        {
            lock (lockObj)
            {
                if (singleton == null)
                {
                    singleton = new ObjectClass();
                }
            }
            return singleton;
        }
    }

 Lock certain loss of performance, if your system to high performance requirements, we have to deal with there is a way to optimize locked: double check the lock

     public static ObjectClass GetSingletone()
        {
            if (singleton == null)
            {
                lock (lockObj)
                {
                    if (singleton == null)
                    {
                        singleton = new ObjectClass();
                    }
                } 
            }
            return singleton;
        }

Use double check the lock, then multiple threads at runtime if the singleton object has been created after not re-enter the lock code segment thereby reducing the performance loss caused by the lock.

Then we come to test wave, enabled 50 threads, you can see HashCode output is consistent.

4, summary

We started talking back to the global or why not agreed to resolve the problem of a single case, because we have developed for it, although there are agreed we can not guarantee that everyone in accordance with the agreement or abuse of a global variable cause problems.

The singleton pattern can better self-management agreement and, of course, we are also likely to abuse a singleton, which requires it to solve the problem of how to use in-depth understanding.

Design mode is not to be applied mechanically, but the scene in line with the fair use when needed.

Although the singleton pattern is relatively simple, but the analysis we see many problems, we need to make better use of better analysis, I hope this blog you some help.

Guess you like

Origin www.cnblogs.com/SunSpring/p/11832454.html