A singleton class in object-oriented programming is a class that can only have one object (an instance of the class) at a time. The new variable also points to the initial instance produced if we try to instantiate the Singleton class after the first time. So any changes we make to any variable within the class through any instance affect the variable of the single instance created and are observable if we access that variable through any variable of the class type declared.
When defining a singleton class, or developing a singleton class, keep the following points in mind:
Create a private function Object() { [native code] }.
Create a static method with the singleton class's return type of object. This static method is written using the concept of lazy initialization.
The Singleton Class serves a specific purpose.
The fundamental goal of a Single class is to limit the number of objects that can create to just one. This frequently guarantees that access to resources, such as a socket or database connection, is controlled.
Because it restricts instance creation, memory space waste does not occur using the singleton class. Because this will only be created once rather than every time a new request is performed.
This single object can be used multiple times depending on the requirements. This is why the Singleton design in Java is commonly used in multi-threaded and database applications for caching, logging, thread pooling, configuration settings, and much more.
For example, if we have a license and only have one database connection or our JDBC driver does not support multithreading, the Singleton class comes into play. It ensures that only a single connection or thread can use the connection at any given moment.
In Java, how do you design/create a singleton class?
We must follow the steps outlined below to construct a singleton class:
1. Make sure there is only one instance of the class.
2. Give that instance global access by
Declaring the class's constructors to be private.
Including a static method that returns the instance's reference. The static methods are written using the lazy initialization principle.
A private static variable is used to hold the instance.
Runtime class, Action Servlet, and Service Locator are singleton classes. The singleton class also includes private constructors and factory methods.
What is the difference between Normal and Singleton Classes?
When it comes to instantiating the class's object, a Singleton class differs from other classes. A java function Object() { [native code] } is used to create a standard class. The getInstance() method, on the other hand, is used to create a singleton class.
Another distinction is that a regular class vanishes at the end of an application's lifecycle, whereas a singleton class does not.
Singleton Class Pattern Variations
The singleton design pattern is divided into two types:
Early Instantiation: At the time of loading, the object is created.
Lazy Instantiation: The object is created according to the specifications.
Let's look at how the singleton class differs from a regular class in Java. The difference is in the way of instantiation: for a regular class, we use the function Object() { [native code] }, whereas for a singleton class, we use the getInstance() function, as we'll see in Example 1 below. In general, to avoid confusion, we can use the class name as the method name when defining this method, as shown in Example 2 below.
Example 1:
// Java program implementing Singleton class
// with using getInstance() method
// Class 1
// Helper class
class Singleton {
// Static variable reference of single_instance
// of type Singleton
private static Singleton single_instance = null;
// Declaring a variable of type String
public String s;
// Constructor
// Here we will be creating private constructor
// restricted to this class itself
private Singleton()
{
s = "Hello I am a string part of Singleton class";
}
// Static method
// Static method to create instance of Singleton class
public static Singleton getInstance()
{
if (single_instance == null)
single_instance = new Singleton();
return single_instance;
}
}
// Class 2
// Main class
class SingletonExample {
// Main driver method
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();
// Instantiating Singleton class with variable z
Singleton z = Singleton.getInstance();
// Printing the hash code for above variable as
// declared
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());
// Condition check
if (x == y && y == z) {
// Print statement
System.out.println(
"Three objects point to the same memory location on the heap i.e, to the same object");
}
else {
// Print statement
System.out.println(
"Three objects DO NOT point to the same memory location on the heap");
}
}
}
In a singleton class, when we first-time call the getInstance() method, it creates an object of the class with the single name instance and returns it to the variable. Because a single instance is a static variable, it is set to some object instead of null. Because a single instance is not null, the getInstance() method returns to the variable instead of instantiating the Singleton class again the next time we call it. This part is done by if condition.
In the main class, we instantiate the singleton class with 3 objects x, y, z by executing the static function getInstance(). But, following object x, variables y and z are pointed to object x, as illustrated in the diagram. Hence, if we modify the variables of object x, that is reflected when we access the variables of objects y and z. Also, updating the variables of object z is reflected when we access the variables of objects x and y.
Now we are done 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 program implementing Singleton class
// with method name as that of class
// Class 1
// Helper class
class SingletonExample2 {
// Static variable single_instance of type Singleton
private static Singleton single_instance = null;
// Declaring a variable of type String
public String s;
// Constructor of this class
// Here private constructor is is used to
// restricted to this class itself
private Singleton()
{
s = "Hello I am a string part of Singleton class";
}
// Method
// Static method to create instance of Singleton class
public static Singleton Singleton()
{
// To ensure only one instance is created
if (single_instance == null) {
single_instance = new Singleton();
}
return single_instance;
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Instantiating Singleton class with variable x
Singleton x = Singleton.Singleton();
// Instantiating Singleton class with variable y
Singleton y = Singleton.Singleton();
// instantiating Singleton class with variable z
Singleton z = Singleton.Singleton();
// Now changing variable of instance x
// via toUpperCase() method
x.s = (x.s).toUpperCase();
// Print and display commands
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");
// Now again changing variable of instance x
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);
}
}
0 Comments