HowTo DesignPattern Singleton

From Frederick Chapleau Wiki

Jump to: navigation, search

Design Pattern Series

Singleton Design Pattern

C# Code Example

    public class SingletonTest
    {
 
        #region Singleton
 
        /// <summary>
        /// Private static variable representing the single intance of the class
        /// </summary>
        private static SingletonTest _instance;
 
        /// <summary>
        /// This constructor is private, so, the only class that can create it, is... me.
        /// </summary>
        private SingletonTest()
        {
        }
 
        /// <summary>
        /// The Instance public property is the accessor to the single instance of the
        /// class. This is static because the constructor is private, so it's the only way to
        /// access a property 
        /// </summary>
        public static SingletonTest Instance
        {
            get
            {
 
                // if the instance is not yet created,
                if (_instance == null)
                {
                    // We create the only intance of our self
                    _instance = new SingletonTest();
 
                    // Here even if the _lst member variable is private it can be accessed
                    // via the external, because the external class is the class itself
                    // so, the private variables are accessible
                    _instance._lst = new ArrayList();
                }
 
                // and we return the only instance
                return _instance;
            }
        }
 
        #endregion
 
        /// <summary>
        /// This should not be static, even if there is only on intance of it
        /// </summary>
        private ArrayList _lst;
 
        /// <summary>
        /// This is accessible only by typing SingletonTest.Instance.SingleList
        /// </summary>
        public ArrayList SingleList
        {
            get
            {
                return _lst;
            }
        }
    }
Personal tools