Use the Singleton pattern for a new Java class Stdout you need to write that can
ID: 3701746 • Letter: U
Question
Use the Singleton pattern for a new Java class Stdout you need to write that can have just one instance. A programmer can use the instance to print text lines (String objects) to the terminal with the method printline():
public class Stdout {
public void printline(String s) {
... // print s to System.out
}
... // fill in the dots
}
Make sure the pattern is implemented correctly (e.g. just one instance can be created).
Notice that the printline() function is NOT static.
Write a main(....) method to test your code.
Explanation / Answer
/****** I have provided the Complete class Implementation . I have difined the singleton pattern by using double locking system. I have created this design pattern thread safe. I have created main method to test the program. I tried to create two instance but if you see i have used equals method to check whether both the instances are same. This verifies that we are able to create only single instance of the class.
*****/
package learning;
public class Stdout {
private static Stdout instance;
private Stdout(){
}
public static Stdout getInstance(){
if(instance == null){
synchronized (Stdout.class) {
if(instance == null){
instance = new Stdout();
}
}
}
return instance;
}
public void printline(String s) {
System.out.println(s);
}
public static void main(String args[]){
Stdout std1 = Stdout.getInstance();
std1.printline("India");
Stdout std2 = Stdout.getInstance();
std2.printline("England");
if(std1.equals(std2)){
System.out.println("Both instances are equal");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.