Is it bad to wrap singleton instance methods in static methods?

727 views Asked by At

Is there a con to implementing a singleton that wraps instance methods with static ones?

For example:

    public void DoStuff() { instance._DoStuff(); }
    private void _DoStuff() {

        ...
    }

And of course instance would be static. But it would be nicer to call:

Singleton.DoStuff();

Instead of:

Singleton.GetInstance().DoStuff();
1

There are 1 answers

3
jcfore21 On

I think it depends.

First the GetInstance() really should be used for getting an object back and then using that else where in your code. The Singleton should just help guarantee a single instance of that object exists.

Next if you want to make DoStuff static go ahead, though you have to know to call it that way everywhere else in your code.

So you really have this difference:

var instance = Singleton.GetInstance();
...
instance.DoStuff ()

Vs

Singleton.DoStuff ()

This means that you can pass a singleton object around and not have to know static calls.

Also, I have to mention that Singletons if not used properly can lead to a nightmare in unit testing: http://misko.hevery.com/2008/08/25/root-cause-of-singletons/