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.

Vivek Vermani
  • 1,876
  • 15
  • 37

3 Answers3

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.

chrylis -cautiouslyoptimistic-
  • 67,584
  • 19
  • 106
  • 140
  • 1
    Thanks. Understood. I believe inability to participate in Runetime Polymorphism is the biggest reason we never use this implementation. Great. Thanks again. – Vivek Vermani Jan 24 '14 at 03:10
  • 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. – Vivek Vermani Jan 24 '14 at 03:24
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

Jay Steven Perry
  • 1,501
  • 1
  • 15
  • 26
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.

Community
  • 1
  • 1
J0e3gan
  • 8,287
  • 9
  • 48
  • 76