design-pattern

The one of the simplest design patterns is Singleton pattern. This pattern ensures that a class has only one instance in the whole application and provides a global point of access to it.

In our application sometime we need such type of object, which will be created only one time in the entire application life cycle. That means, there will be only one object in the whole application and everyone will be able to access that one object.

We can create this type of class by using static. Then we can access that class without creating new instance.

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

During creation, we need to consider about multithreaded environment. Then multiple resource can access that class in 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 checked lock
            {
                lock (_lock)
                {
                    if (uniqueInstance == null)
                    {
                        uniqueInstance = new Singleton();
                    }
                }
            }
            return uniqueInstance;
        }
 }

Here double checked lock approach is used in order to overcome eagerly created instance problem.

Though, singleton pattern is very simple, but we have to use it very carefully. Unless it will decrease the application performance.


Source link

Leave a Reply

Your email address will not be published. Required fields are marked *