Java Singleton Pattern
- by Spencer
I'm used the Singleton Design Pattern
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
My question is how do I create an object of class Singleton in another class?
I've tried:
Singleton singleton = new Singleton();
// error - constructor is private
Singleton singleton = Singleton.getInstance();
// error - non-static method cannot be referenced from a static context
What is the correct code?
Thanks,
Spencer