Singleton

This lesson discusses all the different ways of creating singleton objects in Java.

What is the singleton pattern?

Show Answer
Did you find this helpful?
Press + to interact
Java
class Demonstration {
public static void main( String args[] ) {
Superman superman = Superman.getInstance();
superman.fly();
}
}
class Superman {
private static Superman superman = new Superman();
private Superman() {
}
public static Superman getInstance() {
return superman;
}
public void fly() {
System.out.println("I am flyyyyinggggg ...");
}
}
  • The next approach is to lazily create the singleton object. Lazy intialization means delaying creating a resource till the time of its first use. This saves precious resources if the singleton object is never used or is expensive to create. First, let's see how the pattern will be implemented in a single threaded environment.

    Singleton initialization in static block

    public class Superman {
        private static Superman superman;
    
        private Superman() {
        }
    
        public static Superman getInstance() {
    
            if (superman == null) {
                superman = new Superman();
            }
    
            return superman;
        }
    }
    
...