Search code examples
c#design-patternssingleton

Singleton Properties


Ok, if I create a singleton class and expose the singleton object through a public static property...I understand that.

But my singleton class has other properties in it. Should those be static? Should those also be private?

I just want to be able to access all properties of my singleton class by doing this:

MySingletonClass.SingletonProperty.SomeProperty2

Where SingletonProperty returns me the single singleton instance. I guess my question is, how do you expose the other properties in the singleton class..make them private and then access them through your public singleton static property?

Or should all your other properties and methods of a singleton be public non-static?


Solution

  • Once you get the SingletonProperty (which is the single instance of an Object), anything after that can be implemented as if you were creating a class to be instanciated because the Singleton is really a single instance of a regular Object.

    For example, the following Singleton (obviously not the best Singleton design, but bear with me) offers up two public Properties called Value and Name:

    public class MySingleton
    {
        private static MySingleton _instance;    
    
        private MySingleton() { }
    
        public static MySingleton Instance
        {
            get
            {
                if(_instance == null)
                    _instance = new MySingleton();
    
                return _instance;
            }
        }
    
        // Your properties can then be whatever you want
        public string Value { get; set; }
    
        public string Name { get; set; }
    }
    

    Accessing these properties would look like:

    MySingleton.Instance.Name = "StackOverflow";
    
    MySingleton.Instance.Value = "Rocks!";