w3resource

Implementing the Singleton Pattern in Java

Java Constructor: Exercise-10 with Solution

Constructor for Singleton Pattern
Write a Java program to create a class called Singleton that ensures only one instance of the class can be created. Implement a private constructor and a public static method to get the single instance of the class. Print a message indicating the creation of the instance.

Sample Solution:

Java Code:

Singleton.java

// Define the Singleton class
public class Singleton {
    // Private static variable to hold the single instance
    private static Singleton singleInstance = null;

    // Private constructor to prevent instantiation
    private Singleton() {
        // Print a message indicating the creation of the instance
        System.out.println("Singleton instance created.");
    }

    // Public static method to get the single instance of the class
    public static Singleton getInstance() {
        // If the single instance is null, create a new instance
        if (singleInstance == null) {
            singleInstance = new Singleton();
        }
        // Return the single instance
        return singleInstance;
    }

    // Main method to test the Singleton class
    public static void main(String[] args) {
        // Get the single instance of Singleton
        Singleton instance1 = Singleton.getInstance();
        // Try to get another instance of Singleton
        Singleton instance2 = Singleton.getInstance();

        // Check if both instances are the same
        if (instance1 == instance2) {
            System.out.println("Both instances are the same.");
        } else {
            System.out.println("Instances are different.");
        }
    }
}

Output:

Singleton instance created.
Both instances are the same.

Explanation:

  • Define the Singleton class:
    • The Singleton class is defined with the keyword class.
  • Private static variable to hold the single instance:
    • A private static variable singleInstance of type Singleton is declared to hold the single instance of the class.
  • Private constructor to prevent instantiation:
    • A private constructor Singleton() is defined to prevent the instantiation of the class from outside.
    • Inside the constructor, a message is printed indicating the creation of the instance.
  • Public static method to get the single instance of the class:
    • A public static method getInstance() is defined to return the single instance of the class.
    • If the singleInstance is null, a new instance of the Singleton class is created.
    • The method returns the singleInstance.
  • Main method to test the Singleton class:
    • The main method is defined to test the Singleton class.
    • Get the single instance: The getInstance() method is called to get the single instance of Singleton.
    • Try to get another instance: The getInstance() method is called again to try to get another instance of Singleton.
    • Check if both instances are the same: An if statement checks if instance1 and instance2 are the same. If they are, a message is printed indicating that both instances are the same.

Note on Constructors:

In the above exercise, the constructors for the Singleton class work by:

  • Private Constructor: The constructor is private, preventing the instantiation of the class from outside. This ensures that only one instance of the class can be created.
  • Static Method for Instance Retrieval: The getInstance() method provides a controlled way to access the single instance of the class. It checks if the instance already exists and creates it if it does not, ensuring that only one instance of the class is ever created.
  • Instance Control: The Singleton pattern uses a private static variable to hold the single instance, maintaining control over the class instantiation and ensuring that all references to the class point to the same instance.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java Constructor Previous: Creating a Java Classroom Class with Array Initialization.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/constructor/java-constructor-exercise-10.php