Singleton Example
The following code is taken from Geeks for Geeks. It shows how to write a Singleton. Test code is also shown.
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 you are not familiar with synchronized, you can delete it
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
A message logging system is an iconic example of the use of the Singleton Design Pattern. Write a MessageLogger class as a singleton. In addition to the code needed to implement the Singleton design pattern, also add a non-static method called logMessage() that logs a given message (a string) into a file. Add another non-static method called printAll() that causes all the messages that have thus far been logged to be printed on the console.
Create and open the file that logs the messages inside the private constructor of the MessageLogger. Use a text file called "msgs.txt" as the name of the file.
Also write a main method that gets access to the MessageLogger object, logs a few messages and then prints them.
Hint: For this lab, you may want to use PrintWriter. If you choose to use this class, it is important to set the append option to true so that you can append new text to an existing file. The example below shows how to do this:
PrintWriter pw = new PrintWriter(new FileOutputStream( new File("persons.txt"), true /* append = true */));