Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

singleton- pattern #3054

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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");
}
}
}