Skip to content

Commit

Permalink
singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
seemaPatl committed Oct 8, 2024
1 parent 084817f commit 7608d29
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions singleton-pattern
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// 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 SingleTon{
// 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");
}
}
}

0 comments on commit 7608d29

Please sign in to comment.