简体   繁体   中英

C# Singleton Pattern

I use the singleton pattern in a lot of places, sometimes the constructor does nothing, other times it's initialising things. I wondered if there was a way to set up an abstract class to minimise my code repetition a bit, ie I don't need public static readonly Singleton _Instance = new Singleton(); in every single class, just one base class. I understand interfaces are not an option.

I've tried using the following (taken from here );

public abstract class Singleton<T> where T : new()
{
    static Singleton()
    {
    }

    private static readonly T _Instance = new T();

    public static T Instance
    {
        get { return _Instance; }
    }
}

The problem with this is that I can't override the constructor for the cases where I need to initialise things. Is what I'm trying to do even possible? Or should I just keep doing what I'm doing and not worry about a base singleton class?

I wondered if there was a way to set up an abstract class to minimise my code repetition a bit

No, there isn't. As soon as you've got an abstract class, you've got a class which can be instantiated multiple times. I've seen various people try to do something like this, but the end result is either not a singleton or is more complicated than just doing what you're already doing.

Is what I'm trying to do even possible? Or should I just keep doing what I'm doing and not worry about a base singleton class?

You shouldn't try to create a base singleton class - but if I were you I'd try to stop using quite so many singletons in the first place. The singleton pattern is very easily overused, and it's tantamount to an anti-pattern. See if you can refactor towards dependency injection, using a configuration which happens to create only one instance of each of these classes, but where that's a matter of configuration rather than enforced by the class itself.

Aside from anything else, unit testing involving singletons tends to be a pain, simply because it's global state which needs cleaning up between tests etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM