Singleton Pattern

The Singleton Pattern ensures a class has only one instance and provides a global point of access to it.

To achieve it we have to do the following

  • Make constructor private
  • Create a public method to get an instance
  • the method will check if the instance is already created then return the same instance or create a new one
class Singleton{
    
    private static Singleton instance;
    
    // constructor is declared private
    private Singleton(){}
    
    // method to instantiate the class
    public Singleton getInstance(){
        if(instance == null){
            return new Singleton();
        }
        return instance;
    }
}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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