Singleton using Static Members and Methods?

This question already has an answer here:

  • Difference between static class and singleton pattern? 36 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.


    A Singleton is a single instance of a class (ie, 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


    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 (ie 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.

    链接地址: http://www.djcxy.com/p/78822.html

    上一篇: Singleton类的优点是什么?

    下一篇: 单身人士使用静态成员和方法?