Static class versus class instance

I have a static class that I use to access my public properties (global for the whole application) and the methods that I use when the application starts. For example, I set some property in a static class, and at runtime I can get the value from the property.

But I can create a non-static class with a singleton pattern and use it in the same way.

Question: Which approach is correct in my case?

+3
source share
5 answers

The example below shows that you can use interfaces with a singleton class (which is not possible with a static class.)

/ .

, , , , , .

public sealed class Settings : IUserStettings, IOSettings
{
    static readonly Settings instance = new Settings();

    static Settings(){ }

    Settings(){ }

    public static Settings Instance
    {
        get { return instance; }
    }

    //-- interface implementation

    public string UserName
    {
        get { throw new NotImplementedException(); }
    }

    // ---etc...

     public string filename
    {
        get { throw new NotImplementedException(); }
    }

    //-- interface implementation
}


public interface IOSettings
{
    string disk {get;}
    string path { get; }
    string filename { get; }
}

public interface IUserStettings
{
    string UserName { get; }
    string Password { get; }
}

, :

    IOSettings iosettings = Settings.Instance as IOSettings;

    if(iosettings!=null){
        Filereader.ReadData(IOSettings iosettings);
    }

    IUserSettings usersettings = Settings.Instance as IUserSettings;

    if(usersettings!=null){
        UserManager.Login(IUserSettings usersettings);
    }
+3

, .

, , . . , .

- (: , , , ..), , , .

+3

1- , , , .net Framework.

Math netural, , , .

2- Singleton , singleton , .

.

+1

, OO/ . SO singleton, . , / , Math

+1

, , , , . , .

0

Source: https://habr.com/ru/post/1764301/


All Articles