Question

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

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

 45  32162  45
1 Jan 1970

Solution

 43

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.

2010-08-20

Solution

 18

Let 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 can't be.
  • Singleton creation may not be threadsafe if it isn't implemented properly. Static is threadsafe.
  • Singleton can be passed around as an object. Static can't be.
  • Singleton can be garbage collected. Static can't be.
  • Singleton is better than static class!
  • More here that I haven't realized yet :)

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

2010-08-20