banner



How To Create Your Own Singleton Class In Java

In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time.
After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created. So whatever modifications we do to any variable inside the class through any instance, it affects the variable of the single instance created and is visible if we access that variable through any variable of that class type defined.

Remember the key points while defining class as singleton class that is while designing a singleton class:

Attention reader! Don't stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course .

  1. Make constructor private.
  2. Write a static method that has return type object of this singleton class. Here, the concept of Lazy initialization is used to write this static method.

Let us brief how the singleton class varies from the normal class in java. Here the difference is in terms of instantiation as for normal class we use constructor, whereas for singleton class we use getInstance() method which we will be peeking out in example 1 as depicted below. In general, in order to avoid confusion, we may also use the class name as method name while defining this method which will be as depicted in example 2 below as follows.

Implementation:


Example 1

JAVA

class Singleton {

private static Singleton single_instance = null ;

public String s;

private Singleton()

{

s = "Hello I am a string part of Singleton class" ;

}

public static Singleton getInstance()

{

if (single_instance == null )

single_instance = new Singleton();

return single_instance;

}

}

class GFG {

public static void main(String args[])

{

Singleton x = Singleton.getInstance();

Singleton y = Singleton.getInstance();

Singleton z = Singleton.getInstance();

System.out.println( "Hashcode of x is "

+ x.hashCode());

System.out.println( "Hashcode of y is "

+ y.hashCode());

System.out.println( "Hashcode of z is "

+ z.hashCode());

if (x == y && y == z) {

System.out.println(

"Three objects point to the same memory location on the heap i.e, to the same object" );

}

else {

System.out.println(

"Three objects DO NOT point to the same memory location on the heap" );

}

}

}

Output

Hashcode of x is 558638686 Hashcode of y is 558638686 Hashcode of z is 558638686 Three objects point to the same memory location on the heap i.e, to the same object

Output explanation:

Singleton class

In a singleton class, when we first-time call getInstance() method , it creates an object of the class with name single_instance and return it to the variable. Since single_instance is static, it is changed from null to some object. Next time, if we try to call getInstance() method, since single_instance is not null, it is returned to the variable, instead of instantiating the Singleton class again. This part is done by if condition.
In the main class, we instantiate the singleton class with 3 objects x, y, z by calling static method getInstance(). But actually after creation of object x, variables y and z are pointed to object x as shown in the diagram. Hence, if we change the variables of object x, that is reflected when we access the variables of objects y and z. Also if we change the variables of object z, that is reflected when we access the variables of objects x and y.
Now we are done with covering all aspects of example 1 and have implemented the same, now we will be implementing Singleton class with method name as that of the class name.

Example 2

JAVA

class Singleton {

private static Singleton single_instance = null ;

public String s;

private Singleton()

{

s = "Hello I am a string part of Singleton class" ;

}

public static Singleton Singleton()

{

if (single_instance == null ) {

single_instance = new Singleton();

}

return single_instance;

}

}

class GFG {

public static void main(String args[])

{

Singleton x = Singleton.Singleton();

Singleton y = Singleton.Singleton();

Singleton z = Singleton.Singleton();

x.s = (x.s).toUpperCase();

System.out.println( "String from x is " + x.s);

System.out.println( "String from y is " + y.s);

System.out.println( "String from z is " + z.s);

System.out.println( "\n" );

z.s = (z.s).toLowerCase();

System.out.println( "String from x is " + x.s);

System.out.println( "String from y is " + y.s);

System.out.println( "String from z is " + z.s);

}

}

Output

String from x is HELLO I AM A STRING PART OF SINGLETON CLASS String from y is HELLO I AM A STRING PART OF SINGLETON CLASS String from z is HELLO I AM A STRING PART OF SINGLETON CLASS   String from x is hello i am a string part of singleton class String from y is hello i am a string part of singleton class String from z is hello i am a string part of singleton class

Output explanation:

In the singleton class, when we first-time call Singleton() method, it creates an object of class Singleton with name single_instance and returns it to the variable. Since single_instance is static, it is changed from null to some object. Next time if we try to call Singleton() method, since single_instance is not null, it is returned to the variable, instead of instantiating the Singleton class again.

This article is contributed by Pavan Gopal Rayapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


How To Create Your Own Singleton Class In Java

Source: https://www.geeksforgeeks.org/singleton-class-java/

Posted by: waterswittionfer93.blogspot.com

0 Response to "How To Create Your Own Singleton Class In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel