Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static class vs. Instance of the class

I have a static class which I use to get access to my public properties (global for whole app) and methods which I use during application run. For example I set some property in static class and during app run time I can get value from property.

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

Question: Which approach is correct in my case?

like image 521
Polaris Avatar asked May 19 '26 06:05

Polaris


2 Answers

The sample below shows that you can use interfaces with a singleton class (which is impossible with static class.)

I prefer this pattern above a large list of static methods/properties or several static classes.

Those interfaces can provide subject specific settings which can even be used as parameters to other methods or classes without that those classes need to know where the settings come from, as long as the contract is respected.

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; }
}

And this can be used in a simple manner as as:

    IOSettings iosettings = Settings.Instance as IOSettings;

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

or

    IUserSettings usersettings = Settings.Instance as IUserSettings;

    if(usersettings!=null){
        UserManager.Login(IUserSettings usersettings);
    }
like image 60
Caspar Kleijne Avatar answered May 21 '26 18:05

Caspar Kleijne


Depends on what you're trying to achieve.

I'd go for static classes to provide utility functions in your application, and mostly avoid singletons for this type of thing. See this question for info about when to use singletons.

If your class represents some sort of entity in the system (Example: A user, a blog post, a product, a student etc.) it should not be a static class, but be instantiated every time you are logically using a separate instance of it.

like image 23
Arve Systad Avatar answered May 21 '26 19:05

Arve Systad