We can replicate a Singleton behavior my making a Class with Static Methods and Member Elements. Other than serialization What's the harm of implementing a singleton using static Body only.
3 Answers
You can't use this pattern to implement a provider for some interface or to allow for subclassing or other alternate behavior. This means that testing becomes more difficult and you can't use dependency injection for anything your static class does.
2 Comments
A Singleton is a single instance of a class (i.e., one object). A block of static code is not an object. It's just code.
It seems there is a definite difference between this:
public class MyClass { public static void doIt() { System.out.println("doIt()"); } } And this:
public class MySingleton { private static MySingleton _singleton = null; private String cantTouchThis; private MySingleton() { cantTouchThis = "Hands off, static block!"; } public static MySingleton newInstance() { if (_singleton == null) { _singleton = new MySingleton(); } return _singleton; } } In the first case, basically all you have is a block of code you can execute by calling MyClass.doIt(). In the second, by calling MySingleton.newInstance() you can get your hands on an honest-to-goodness object.
HTH
Comments
Akwardness or hoop-jumping to unit test such a "singleton" is one potential downside in addition to serialization.
Contrast this with unit testing a true (i.e. instantiable) singleton.
Ultimately, a singleton guarantees a single instance of a class, whereas a static class is not instantiable as @JStevenPerry points out (and I expect you already understand): the two are simply not the same although they can in many ways be employed similarly.