Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton design pattern vs static class

What are the scenarios when Singleton design pattern is preferred over static class & when static class is preferred over Singleton design pattern?

like image 840
WpfBee Avatar asked Nov 29 '22 01:11

WpfBee


2 Answers

This is not really an either or scenario.

Singletons are instances with a static getter, and a private constructor. They are not static classes.

Singleton with certain provisos is a way of ensuring you only have one instance of class.

So the first question is. Do you need an instance, i.e. does this thing have a state, the second question is given how difficult they make unit testing, do you want one at all.

Have a look at the Service Locator pattern, for instance.

like image 165
Tony Hopkinson Avatar answered Dec 06 '22 01:12

Tony Hopkinson


Generally singletons are superior to static classes.

Singleton in contrary to static class:

  • can inherit, and can be inherited;
  • can implement interface;
  • can be serialized;
  • can be passed to other classes;
  • can be disposed.

If you choose static class then you choose concrete, there's no flexibility. However, if you use singleton you have to remember to make the instantiation of it thread safe.

like image 30
Dzienny Avatar answered Dec 06 '22 00:12

Dzienny