Singleton Pattern - Default Property

后端 未结 3 790
暗喜
暗喜 2021-01-21 01:46

I\'ve been studying the Singleton pattern as it is used in the Settings class. Here\'s the relevant code from Settings.Designer.cs for my project AccessTest:

int         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-21 02:08

    There are a great many posts on the singleton pattern but I couldn't find any that address this particular issue. So I thought I'd take a shot at explaining it myself using this example that I created in my secret laboratory with the help of your posts:

    namespace MyProject.Properties                                  
    {                                   
        internal class Singleton                                
        {                               
    
            // Create an instance of the class itself.                          
            private static Singleton instance = new Singleton();                            
    
            // Wrap the instance in a public property.                          
            public static Singleton Instance                            
            {                           
                get {return instance;}                      
            }                           
    
            // Prevent additional references from being created with a private constructor.                         
            private Singleton() { }                         
    
            // Create a non-static variable.                                
            public string nonStatic = "non static";                         
    
        }                               
    }                                   
    

    We know the following about this Singleton class:

    • The 'Instance' public property can only be accessed statically.
    • 'nonStatic' can't be accessed statically, i.e., it can only be accessed via a reference.
    • The private constructor prevents additional references from being created.

    How, then, is it possible to access 'nonStatic' from outside the class?

    The framework resolves the dilemma by endowing the static 'Instance' with magical powers that only exist in a singleton situation: 'Instance' becomes a "bridge" that provides access to any non-statics. Ergo, this form works:

    var value = MyProject.Properties.Singleton.Instance.nonStatic;                                  
    

    Note: The pattern used my Microsoft in the Settings.Designer.cs file appears to not be a true singleton because the default constructor allows additional references to be created.

提交回复
热议问题