Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a Singleton pattern and a static class in Java? [duplicate]

How is a singleton different from a class filled with only static fields?

like image 885
cesar Avatar asked Aug 20 '10 15:08

cesar


2 Answers

Almost every time I write a static class, I end up wishing I had implemented it as a non-static class. Consider:

  • A non-static class can be extended. Polymorphism can save a lot of repetition.
  • A non-static class can implement an interface, which can come in handy when you want to separate implementation from API.

Because of these two points, non-static classes make it possible to write more reliable unit tests for items that depend on them, among other things.

A singleton pattern is only a half-step away from static classes, however. You sort of get these benefits, but if you are accessing them directly within other classes via `ClassName.Instance', you're creating an obstacle to accessing these benefits. Like ph0enix pointed out, you're much better off using a dependency injection pattern. That way, a DI framework can be told that a particular class is (or is not) a singleton. You get all the benefits of mocking, unit testing, polymorphism, and a lot more flexibility.

like image 148
StriplingWarrior Avatar answered Sep 24 '22 21:09

StriplingWarrior


Let's me sum up :)

The essential difference is: The existence form of a singleton is an object, static is not. This conduced the following things:

  • Singleton can be extended. Static not.
  • Singleton creation may not be threadsafe if it isn't implemented properly. Static not.
  • Singleton can be passed around as an object. Static not.
  • Singleton can be garbage collected. Static not.
  • Singleton is better than static class!
  • More here but I haven't realized yet :)

Last but not least, whenever you are going to implement a singleton, please consider to redesign your idea for not using this God object (believe me, you will tend to put all the "interesting" stuffs to this class) and use a normal class named "Context" or something like that instead.

like image 28
instcode Avatar answered Sep 24 '22 21:09

instcode