Home  >  Article  >  Java  >  Singleton Class in Java

Singleton Class in Java

PHPz
PHPzOriginal
2024-08-30 16:00:03790browse

Singleton class restricts the object creation for a class to only one in the java virtual machine. It also helps in providing a global access point to the object. This design pattern is commonly used in caching, Abstract Factory, logging, Prototype, etc. It is also used in core java classes such as java.awt.Desktop, java.lang.Runtime. In java.lang.Runtime, Java provides a class Runtime that signifies the current Runtime Environment where the application is running. This helps in interfacing the application and runtime environment. There should be one object as the JRE is unique. In java.awt.Desktop, class Desktop allows applications to launch a URI or a file with the user’s default browser, mail client, etc. Here also, there must be only one instance of the class.

How does Singleton Class work in Java?

Singleton Class can be created in two ways.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  1. Set the constructor as private in order to limit the creation of an object.
  2. Create a static method to get an instance of the object so that you can handle the creation of the object inside the class only.

Now, let us see the Class UML (Unified Modeling Language) diagram of Singleton Class.

Singleton Class in Java

In the Class UML diagram, the first partition represents the name of a class, the second partition represents the attributes, and the third partition represents the methods. Also, + indicates public attributes or methods, and – indicates private attributes or methods. For example, in our Singleton Class UML diagram, the class name is Singleton, and it has a main method. The main method, getInstance Method and sampleMethod are the only methods that are public in the above diagram. Constructor and instance attribute is set as private as part of our implementation. This public Main method asks for the instance, and getInstance returns it to the main method.

Based on Instantiation, the only difference between normal Java Class and Singleton Class is that we will use a constructor in Java Class whereas, in Singleton, we will be using getInstance() method.

Singleton’s design pattern is of two forms.

  • Lazy Instantiation: Instance creation when required
  • Early Instantiation: Instance creation at load time.

1. Lazy Instantiation

In Lazy Instantiation, a class instance is created when it is required. It is created in the Synchronized method or block in order to avoid the race conditions that can occur in a multi-threaded environment.

2. Early Instantiation

In Early Instantiation, an instance is created at the load time. Even though this is the simplest approach, it has a disadvantage that the instance creation is regardless of whether it is accessed or not.

An example of Lazy Instantiation and Early Instantiation is explained in the following section.

Implementation of Singleton Class in Java

As discussed above, Singleton Class can be created in Early Instantiation or Lazy Instantiation.

Lazy Instantiation

Following are the steps to implement the Lazy Instantiation.

1. Set Constructor as private.

For Example, we are creating a class, LazyClass. The constructor will be as shown below.

private LazyClass ()
{
}

2. Create a private static instance for the class created.

private static LazyClass instance;

3. Create a static synchronized method that gets the class instance created.

public static synchronized LazyClass getInstance()
{
}

4. In the getInstance() method, first, check whether any instance is present or not. If not found, create one. Else return the instance.

if(instance == null)
{
instance = new LazyClass ();
}
return instance;

Now, let us look into it using sample code.

//Java Program for Lazy Instantiation
public class LazyClass {
private static LazyClass instance;
//set the constructor as private
private LazyClass () {}
//Checks whether an instance is already in the getInstance method
public static synchronized LazyClass getInstance() {
//if instance is not present already, create a new one
if(instance == null) {
instance = new LazyClass ();
}
// if an instance is present, then return it
return instance;
}
//Sample method that is protected from more than one object creation
public void sampleMethod( ) {
System.out.println("sampleMethod for lazy singleton");
}
public static void main(String[] args) {
LazyClass temp=LazyClass.getInstance();
temp.sampleMethod();
}
}

Output:

Singleton Class in Java

Here, instead of creating an instance at load time, it is created inside the synchronized block. For better understanding, a sample method is also given that it is protected from more than one object creation.

Early Instantiation

Now let us see the steps for Early Instantiation. It is similar to Lazy instantiation, except that it does not use any synchronized method or block.

1. Set Constructor as private.

For Example, we are creating a class, EarlyClass. The constructor will be as shown below.

private EarlyClass () ()
{
}

2. Create a private static instance for the class created.

private static EarlyClass <em>ins</em>= new EarlyClass();

3. Create a static method that gets the class instance created.

public static EarlyClass getInstance()
{
}

Following is the sample code for Early Instantiation.

//Java Program for Early Instantiation
public class EarlyClass {
//Create an instance of the class at load time
private static EarlyClass <em>ins</em>= new EarlyClass();
//set the constructor as private
private EarlyClass () {}
//A static method to get the instance
public static EarlyClass getInstance() {
return ins;
}
//A sample method that is protected from more than one object creation
public void sampleMethod() {
System.out.println("sampleMethod for Early singleton");
}
//Main method
public static void main(String[] args) {
EarlyClass tmp = getInstance();
tmp.sampleMethod();
}
}

Output:

Singleton Class in Java

In the above program, an instance is created in load time, and it is returned using the method getInstance(). In addition, the Constructor is set as private as part of singleton instantiation.

Memory saving is the main advantage of using this as an object is reused and not created again and again.

Conclusion

In this document, we have covered how a Singleton Class works with the help of a Class UML diagram, algorithm, and Sample code. Singleton Class is used when we need only one object for a class and a global access point to that object. The two forms, such as Early instantiation and Lazy Instantiation, can be used based on the requirement.

The above is the detailed content of Singleton Class in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Encapsulation in JavaNext article:Encapsulation in Java