design-pattern

The one of the simplest design designs is Singleton pattern. This pattern ensures that a class features only one instance in the whole use and provides a global point connected with access to it.

In each of our application sometime we need many of these type of object, which will be made only one time in the entire use life cycle. That method, there will be only one object in all of application and everyone will be able to gain access to that one object.

We can make this type of class by using fixed. Then we can access the fact that class without creating fresh instance.

public class Singleton
 {
    private Singleton() { }
    public static Singleton CreateInstance()
    {
        return new Singleton();
    }
 }

During creation, we should instead consider about multithreaded setting. Then multiple resource can certainly access that class inside the same time.

public class Singleton
 {
        private volatile static Singleton uniqueInstance;
        private static readonly object _lock = new object();
        private Singleton() { }
        public static Singleton CreateInstance()
        {
            if (uniqueInstance == null)//double examined lock
            {
                lock (_lock)
                {
                    if (uniqueInstance == null)
                    {
                        uniqueInstance = new Singleton();
                    }
                }
            }
            return uniqueInstance;
        }
 }

Here double checked lock approach is used so that you can overcome eagerly created case problem.

Though, singleton design is very simple, but we have to put it to use very carefully. Unless it will cure the application performance.


Source link