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

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.

Leave a Comment