-2
public class Singleton {
  private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
  }

  private Singleton() {
  }

  public static Singleton getInstance() {
    return SingletonHolder.INSTANCE;
  }

  public static void main(String args[]) {
    Singleton s = new Singleton();
    Singleton s2 = new Singleton();
  }
  }

Based on the "Effective Java", a singleton class is something like above.

Suppose we have a main inside this class. We can initiate the singleton class as many times as we want, like

Singleton s1=new Singleton();
Singleton s2=new Singleton();
Singleton s3=singleton.getInstance();
Singleton s4=singleton.getInstance();

A singleton class should be a class that can be only be initiated once, but the compiler will not throw a error if we declare multiple instances above, why?

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
sevenxuguang
  • 177
  • 9

1 Answers1

0

A singleton class should be a class that can only be instantiated once by other classes. This is normally achieved with a private constructor. However, a private constructor cannot prevent instantiation from within the class.

You should read this question, though: What is an efficient way to implement a singleton pattern in Java?

If you follow Joshua Bloch's idea and use an enum to implement your singleton, then you won't be able to break the singleton contract even from within the class.

Community
  • 1
  • 1
Fred Porciúncula
  • 8,533
  • 3
  • 40
  • 57
  • But inside the same package I declare a another class, but I can also initiate as many instances as I want ? I just tried on eclipse but no errors shown.... – sevenxuguang Dec 23 '15 at 18:46
  • Did you use an enum? It's simply not possible to have more than one single instance for an enum type. Also, the compiler will never issue an error saying something like "You've just created two instances of a singleton". A singleton is a pattern, and the compiler will not validate it. – Fred Porciúncula Dec 23 '15 at 18:49
  • I do not use enum. If I can create multiple instances in another class, what is the meaning of creating a "singleton class"? – sevenxuguang Dec 23 '15 at 18:53
  • You can't create multiple instances in another class if you use the strategy you presented on your question or the enum strategy. And that's the point of singletons: keeping only one instance of a particular class for the whole application. – Fred Porciúncula Dec 23 '15 at 18:56
  • But I do can create multiple instances in another class and I use the code above because the eclipse allows me to do so and that is what I am confused at? – sevenxuguang Dec 23 '15 at 18:59
  • You said yourself in your answer you can only create multiple instances from a main method within the singleton class... – Fred Porciúncula Dec 23 '15 at 19:11