jeudi 25 février 2016

Two ways of Singleton design

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?

Aucun commentaire:

Enregistrer un commentaire