0% found this document useful (0 votes)
7 views2 pages

Java Singleton

The document presents a Java implementation of the Singleton design pattern, which ensures that a class has only one instance and provides a global point of access to it. It features a private static instance, a private constructor, and a public method for instance retrieval with lazy initialization. The main class demonstrates the functionality by creating two references to the Singleton instance and confirming they point to the same object.

Uploaded by

shivam9131363438
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Java Singleton

The document presents a Java implementation of the Singleton design pattern, which ensures that a class has only one instance and provides a global point of access to it. It features a private static instance, a private constructor, and a public method for instance retrieval with lazy initialization. The main class demonstrates the functionality by creating two references to the Singleton instance and confirming they point to the same object.

Uploaded by

shivam9131363438
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

//Java Singleton Class

public class Singleton {

// Step 1: Create a private static instance

private static Singleton instance;

// Step 2: Private constructor to prevent instantiation

private Singleton() {

System.out.println("Singleton Instance Created");

// Step 3: Public method to provide access to the instance

public static Singleton getInstance() {

if (instance == null) {

instance = new Singleton(); // Lazy Initialization

return instance;

public void showMessage() {

System.out.println("Hello from Singleton!");

class Main {

public static void main(String[] args) {

Singleton obj1 = Singleton.getInstance();

Singleton obj2 = Singleton.getInstance();


obj1.showMessage();

System.out.println(obj1 == obj2); // true (Both references point to the same


instance)

You might also like