Singleton Pattern

Singleton Pattern

Singleton pattern is a design pattern that restricts the instantiation of a class to one object. Singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.

Sample code to demonstrate singleton pattern

    public class SingleTonclass

    {
        private static SingleTonclass singleTonObject;
        private UserRepository userRepository;
        // private constructor make sure to avoid creating object using new keyword
        private SingleTonclass ()
        {
           userRepository = new UserRepository();
        }
        // public method which will be called
        public Clients GetName(UserInfo userObject)
        {
            //in repository class used Iterator Pattern
            var user = from m in userRepository.GetUserObject(userObject)
                       select m;
            var clientInfo = user.FirstOrDefault();
            return clientInfo;
        }
        public static SingleTonclass CreateInstance()
        {
            // this object will be used with lock, so that it will be always one thread which will be executing
the code

            object myObject = new object();
            // put a lock on myObject. We won't be able to use singleTonObject becuase it will be null. lock is
to make the object thread safe.

            // lock can't be worked with null objects.
            lock (myObject)
            {
                // check whether the instance was there. If it's not there, then create an instance.
                if (singleTonObject == null)
                    singleTonObject = new SingleTonclass ();
            }
            return singleTonObject;
        }
    }
 

Calling Method

public ViewResult Index(UserInfo userObject)       
{
//singleton Implementation goes here....
SingleTonclass myObject = SingleTonclass.CreateInstance();
var clientInfo = myObject.GetName(userObject);
return view(clientInfo);

}