Singleton Class in Java

Singleton Design Pattern says that just "if a class that has only one instance and provides a global point of access to it is called singleton".

In other words, a class must ensure that only single instance(object) should be created and single object can be used by all other classes.


Important points to create a singleton class: -

  1. We can make constructor as private. So that We can not create an object outside of the class.
  2. This property is useful to create singleton class in java.
  3. Singleton pattern helps us to keep only one instance of a class at any time.
  4. The purpose of singleton is to control object creation by keeping private constructor.

 

package com.singleton;
public class MySingleTon {
    private static MySingleTon myObj;
        // Create private constructor
    private MySingleTon(){         
    }
    // Create a static method to get instance.
    public static MySingleTon getInstance(){
        if(myObj == null){
            myObj = new MySingleTon();
        }
        return myObj;
    }     
    public void getSomeThing(){
        // do something here
        System.out.println("I am here....");
    }
     public static void main(String a[]){
        MySingleTon st = MySingleTon.getInstance();
        st.getSomeThing();
    }
}

Related Articles

post a comment