Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton Pattern - Default Property

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:

internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{        
    private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

    public static Settings Default
    {
        get
        {
            return defaultInstance;
        }
    }

    public string applicationSetting1
    {
        get
        {
            return ((string)(this["applicationSetting1"]));
        }
    }
}

What is unclear to me is why the property 'applicationSetting1' is accessed through another property 'Default' like this:

var value = AccessTest.Properties.Settings.Default.applicationSetting1;

I'm running VS2013 C# and 4.5.

like image 896
Tim Bostwick Avatar asked Aug 11 '26 19:08

Tim Bostwick


1 Answers

Because the defaultInstance is static, whereas applicationSetting1 is not. This effectively makes defaultInstance your manager of the class instance. When you call a static method on a class, it doesn't need instantiating,, so you know that you can maintain only a single instance of the class.

Responding to your comments:

Default is NOT the parent of applicationSetting1; Default is simply a global function that returns an instance of applicationSetting1. In the case of a singleton pattern, that always happens to be the same instance.

Manager is my term. To better describe what a singleton pattern is, think of it as a global variable with a single accessor (which I was describing as a manager, simply because it manages the lifecycle of the variable).

like image 149
Paul Michaels Avatar answered Aug 14 '26 09:08

Paul Michaels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!