Pages

Singleton class in java

Singleton class in java

  • In object oriented programming, singleton is a class that can have only one object(an instance of class) at a time.
  • After first time, if we try to instantiate the Singleton class multiple times, the new variable also points to the first instance created.
  • It is used to provide global point of access to the object. 
  • In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects.
How to design a singleton class:
  1. Make construct as private
  2. Need to write static method which will return object of singleton class.(lazy initialization concept)
Java program on singleton class:

public class singleton {

private static singleton ston = null;

public String s1 = "stringvariable";


private singleton() {
System.out.println("private constructor");
}


public static singleton getInstance() {
if (ston == null)
ston = new singleton();

return ston;
}


public static void main(String[] args) {
// instantiating Singleton class with variable x
singleton x = singleton.getInstance();
// instantiating Singleton class with variable y
singleton y = singleton.getInstance();
// changing variable of instance x
x.s1 = (x.s1).toUpperCase();
System.out.println(x.s1);
System.out.println(y.s1);
}
}
Output:
Singleton class in java
Singleton class in java

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.