0

I'm trying to learn about the Singleton design pattern and I found two different ways of only creating 1 instance.

public class Singleton {
   private static Singleton instance; // attributes omitted
   private Singleton() {
    // omissions
   }

public static Singleton instance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
}
// other methods omitted
}

public class Singleton {
   private static int bound = 1;
   public Singleton() {
    if (bound == 0) {
        throw new RuntimeException(
        "Singleton: No more objects must be created");
    }
    bound--;
}
}

Which is preferred to use and why? Are they equally as good?

Michael
  • 634
  • 5
  • 13
  • 33

3 Answers3

3

Not sure about the Java way to do it but in my opinion I would just use the first way. I consider that it would be bad to throw and exception in your constructor and to expose publicly

Since you only want to get your unique instance the constructor should be private.

Raul A.
  • 223
  • 4
  • 10
2

The first of your methods is a common way to try to implement a lazily-created singleton. It has some issues such as lack of thread safety, although they can be overcome via mechanisms like synchronization.

The second of your methods is truly vile. Exceptions should only be used to indicate exceptional conditions in the code. If you don't want somebody to create an instance of the class, don't let them - you can take control of the instantiation. Forcing them to catch an exception is a totally unnecessary burden on users of your class. (And it's not thread safe either).


A single-element enum is the best and easiest way to create a singleton.

However, there are certain circumstances in which you can't use an enum, for instance if your class needs to extend another class:

  • If you can initialize the instance eagerly, just do that:

    class Singleton /* extends Blah */ {
      private static final Singleton INSTANCE = new Singleton();
    
      static Singleton getInstance() { return INSTANCE; }
    }
    
  • If you want to defer initialization until it is required, you can use the lazy holder idiom:

    class Singleton /* extends Blah */ {
      private static class Holder {
        private static final Singleton INSTANCE = new Singleton();
      }
    
      static Singleton getInstance() {
        return Holder.INSTANCE;
      }
    }
    

    The Holder class is not initialized until getInstance() is called, so the Singleton instance is not created until then.

It should be noted that singletons are considered by some to be a design antipattern.

Community
  • 1
  • 1
Andy Turner
  • 122,430
  • 10
  • 138
  • 216
-1

Don't use either. As of Java 5, the preferred technique is to use an enum with a single value, usually named INSTANCE.

chrylis -cautiouslyoptimistic-
  • 67,584
  • 19
  • 106
  • 140