What is Singleton class in Java?

0

 What is Singleton class in Java?


It is a special class in java that is used to provide restriction to create multiple objects, it provides only a single object creation of class using the static reference method. static block and underclass using the final modifier.

It is used to implement the Singleton design pattern in Java Application.


Rules of Singleton class:-


1)  Singleton class constructor should be private to restrict create a new object from any external method or main()


2)  create a static reference type  method and create an object when static reference is null



It is used to provide a Singleton design pattern in a project where we want to create only a single object for all business class that is used in the project.


CODE OF SINGLETON DESIGN PATTERN:-


class Singletion

{

    private static Singletion obj;

    static String s="";

    private Singletion()

    {


    }

    public static Singletion getInstance()

    {

          if(obj==null)

          {

             obj = new Singletion();

             s="Object created";

          }

          else

          {

              s = "Object Already Created";

          }

          return obj;

    }


    public static void showMessage()

    {

       System.out.println(s);

    }



}


class Client

{

    public static void main(String args[])

    {

        Singletion obj = Singletion.getInstance();

        obj.showMessage();  

        Singletion obj1 = Singletion.getInstance();

        obj1.showMessage();   


    }


}







                                    







Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)