5

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.

1
  • 1
    I din't found my answer in that thread. I believe the other thread is about demerits of singleton. I am asking why we can't replace the commin used implementation with static body. Commented Jan 24, 2014 at 3:07

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Understood. I believe inability to participate in Runetime Polymorphism is the biggest reason we never use this implementation. Great. Thanks again.
and i believe its related because we can't override static methods. Great. I knew there are few other things like serialization , lazy loading etc but i was missing this very important reason.
4

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

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.