Monday, March 29, 2010

To make an instance of an object globally available and guarantee that only one instance of the class

Singleton provides a global,
Making the class create a single instance of itself.
public class SampleSingleton   
{         //SingleTon   
        private static volatile SampleSingleton _instance;   
        private static object syncRoot = new Object();   
        public static SampleSingleton Instance   
        {   
            get  
            {   
                if (_instance == null)   
                {   
                    lock (syncRoot)   
                    {   
                        if (_instance == null)   
                        {   
                            _instance = new SampleSingleton();   
                        }   
                    }   
                }   
  
                return _instance;   
            }   
        }   
  
        public string getDisplay()   
        {   
            return "SingleTon";   
        }   
    }   
///Access singleton    
 SampleSingleton.Instance.getDisplay();