mercredi 27 mai 2015

Idea- using optional singletons

I'm writing a PCL in .NET and I have a stateless class that acts only on the parameters given to its methods. I wanted to make it static, but it already implements two interfaces, so that's out of the question; in the end, I resolved to make it a singleton. However, I know there is a lot of negative stigma associated with the singleton; after hours of internal debate, I'm settling on something like this:

class OptionalSingleton : IInterfaceA, IInterfaceB
{
    private static readonly OptionalSingleton _SharedInstance = 
        new OptionalSingleton();

    public static OptionalSingleton SharedInstance
    {
        get { return _SharedInstance; }
    }

    // default, public constructor

    // rest of implementation
}

I settled on this because a full Singleton encourages tight coupling and Singleton.Instance rather than passing it around as a parameter, while I still want to encourage people to use a shared instance rather than create their own container classes or use new Class(), which is kind of pointless. Because again, this is stateless and therefore thread-safe.

Is this a good idea or are there pitfalls in this I'm not seeing?

Aucun commentaire:

Enregistrer un commentaire