Design Pattern: Singleton

Early instantiation:

Ref https://www.youtube.com/watch?v=sH_f6LxVhPw&list=PLW7fU_8SZVrtz-riKwgnx6u6U0QvYtVOk&index=5

// Online Java Compiler
// Use this editor to write, compile and run your Java code online
class Apple{
    private Apple(){
        System.out.println("Hello, World!");
    }
}

class Main {
    public static void main(String[] args) {
        //Apple obj1 = new Apple();
        //Apple obj2 = new Apple();
        //Singleton obj = new Singleton(); // we cannot use it directly
        //Singleton obj = new Singleton();
        Singleton obj = Singleton.getinstance();
        obj.getMessage();

        Singleton obj2 = Singleton.getinstance();
        //obj1==obj2;
        
        }
}
public class Singleton {
    
    private static Singleton instance = new Singleton();
    
    private Singleton(){}; 
    
    public static Singleton getinstance(){
        return instance;        
    }
    
    public void getMessage(){
        System.out.println("Singleton Class");
    }
    
}

Lazy Instantiation: https://www.youtube.com/watch?v=4lzKgUl7Cjk&list=PLW7fU_8SZVrtz-riKwgnx6u6U0QvYtVOk&index=6

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *