0

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();
sk84z
  • 193
  • 1
  • 3
  • 10

1 Answers1

0

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/

jcfore21
  • 72
  • 6
  • Ahh, so as long as I implement it properly, its okay. Thank you! – sk84z Jul 27 '16 at 22:31
  • Yes, I think that's accurate. Though I would be careful putting a bunch of static calls everywhere. Its easier to do dependency injection without them - if you ever do that. Which I recommend looking into. – jcfore21 Jul 28 '16 at 14:07
  • I have a very basic understanding of dependency injection to be honest.. I'll do research into that! That's for pointing that out as well. – sk84z Jul 28 '16 at 20:18