The Wayback Machine - https://web.archive.org/web/20240716230417/https://www.geeksforgeeks.org/singleton-class-java/
Open In App

Singleton Method Design Pattern in Java

Last Updated : 07 Nov, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

In object-oriented programming, a java singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Java Singleton classes, the new variable also points to the first instance created. So whatever modifications we do to any variable inside the class through any instance, 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 a class as a singleton class that is while designing a singleton class:

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

Purpose of Singleton Class

The primary purpose of a java Singleton class is to restrict the limit of the number of object creations to only one. This often ensures that there is access control to resources, for example, socket or database connection.

Memory space wastage does not occur with the use of the singleton class because it restricts instance creation. As the object creation will take place only once instead of creating it each time a new request is made.

We can use this single object repeatedly as per the requirements. This is the reason why multi-threaded and database applications mostly make use of the Singleton pattern in Java for caching, logging, thread pooling, configuration settings, and much more.

For example, there is a license with us, and we have only one database connection or suppose our JDBC driver does not allow us to do multithreading, then the Singleton class comes into the picture and makes sure that at a time, only a single connection or a single thread can access the connection.

How to Design/Create a Singleton Class in Java?

To create a singleton class, we must follow the steps, given below:

1. Ensure that only one instance of the class exists.

2. Provide global access to that instance by

  • Declaring all constructors of the class to be private.
  • Providing a static method that returns a reference to the instance. The lazy initialization concept is used to write the static methods.
  • The instance is stored as a private static variable.

Example of singleton classes is Runtime class, Action Servlet, and Service Locator. Private constructors and factory methods are also an example of the singleton class.

Difference between Normal Class and Singleton Class

We can distinguish a Singleton class from the usual classes with respect to the process of instantiating the object of the class. To instantiate a normal class, we use a java constructor. On the other hand, to instantiate a singleton class, we use the getInstance() method.

The other difference is that a normal class vanishes at the end of the lifecycle of the application while the singleton class does not destroy with the completion of an application.

Forms of Singleton Class Pattern

There are two forms of singleton design patterns, which are:

  • Early Instantiation: The object creation takes place at the load time.
  • Lazy Instantiation: The object creation is done according to the requirement.

Implementation: Let us briefly 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 a constructor, whereas for singleton class we use the 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 the method name while defining this method which will be depicted in example 2 below as follows.

Example 1:

Java




// 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 synchronized Singleton getInstance()
    {
        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.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");
        }
    }
}


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 the getInstance() method, it creates an object of the class with the 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 the 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, and z by calling the static method getInstance(). But actually, after the 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 the Singleton class with the method name as that of the class name.

Example 2:

Java




// Java program implementing Singleton class
// with method name as that of class
 
// Class 1
// Helper class
class Singleton {
    // 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 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 z
        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



Explanation: In the singleton class, when we first-time call Singleton() method, it creates an object of class Singleton with the 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.

Further Read: Java Design Patterns Tutorial



Previous Article
Next Article

Similar Reads

Difference Between Singleton and Factory Design Pattern in Java
Design patterns are essential tools for creating maintainable and scalable software. Two commonly used design patterns in Java are the Singleton and Factory patterns. This article provides an introduction to the Singleton and Factory design patterns with examples. Singleton Design Pattern in JavaThe Singleton pattern is a creational design pattern
3 min read
Java Singleton Design Pattern Practices with Examples
In previous articles, we discussed about singleton design pattern and singleton class implementation in detail. In this article, we will see how we can create singleton classes. After reading this article you will be able to create your singleton class according to your requirement, which is simple and without bottlenecks. There are many ways this
6 min read
Difference Between Singleton Pattern and Static Class in Java
Singleton Pattern belongs to Creational type pattern. As the name suggests, the creational design type deals with object creation mechanisms. Basically, to simplify this, creational pattern explains to us the creation of objects in a manner suitable to a given situation. Singleton design pattern is used when we need to ensure that only one object o
6 min read
How to prevent Singleton Pattern from Reflection, Serialization and Cloning?
Prerequisite: Singleton Pattern In this article, we will see what various concepts can break the singleton property of a class and how to avoid them. There are mainly 3 concepts that can break the singleton property of a class. Let's discuss them one by one. Reflection: Reflection can be caused to destroy singleton property of the singleton class,
6 min read
Collections.singleton() method in Java with example
java.util.Collections.singleton() method is a java.util.Collections class method. It creates a immutable set over a single specified element. An application of this method is to remove an element from Collections like List and Set. Syntax: public static Set singleton(T obj) and public static List singletonList(T obj) Parameters: obj : the sole obje
3 min read
Singleton and Prototype Bean Scopes in Java Spring
Bean Scopes refers to the lifecycle of Bean that means when the object of Bean will be instantiated, how long does that object live, and how many objects will be created for that bean throughout. Basically, it controls the instance creation of the bean and it is managed by the spring container.Bean Scopes in Spring The spring framework provides fiv
8 min read
Advantages and Disadvantages of using Enum as Singleton in Java
Enum Singletons are new ways of using Enum with only one instance to implement the Singleton pattern in Java. While there has been a Singleton pattern in Java for a long time, Enum Singletons are a comparatively recent term and in use since the implementation of Enum as a keyword and function from Java 5 onwards. Advantages of using Enum as Singlet
3 min read
Private Constructors and Singleton Classes in Java
Let's first analyze the following question: Can we have private constructors ? As you can easily guess, like any method we can provide access specifier to the constructor. If it's made private, then it can only be accessed inside the class. Do we need such 'private constructors ' ? There are various scenarios where we can use private constructors.
2 min read
Singleton Class in Android
The Singleton Pattern is a software design pattern that restricts the instantiation of a class to just "one" instance. It is used in Android Applications when an item needs to be created just once and used across the board. The main reason for this is that repeatedly creating these objects, uses up system resources. The identical object should ther
4 min read
Pattern pattern() method in Java with Examples
The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression. Syntax: public String pattern() Parameters: This method does not accepts anything as parameter. Return Value: This
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg