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

Singleton Pattern Example

The document describes the implementation of the Singleton Design Pattern using a Logger class in Java. It demonstrates how to ensure that only one instance of the Logger can be created by using the getInstance() method, and verifies this by comparing two references. The program logs messages from both references and confirms they point to the same instance.

Uploaded by

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

Singleton Pattern Example

The document describes the implementation of the Singleton Design Pattern using a Logger class in Java. It demonstrates how to ensure that only one instance of the Logger can be created by using the getInstance() method, and verifies this by comparing two references. The program logs messages from both references and confirms they point to the same instance.

Uploaded by

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

Exercise 1: Implementing the Singleton Pattern

Program:
1. Logger.java
class Logger{
private static Logger instance;
private Logger(){
System.out.println("Logger Initializer");
}
public static Logger getInstance(){
if(instance==null)
instance=new Logger();
return instance;
}
public void log(String message){
System.out.println("Log: "+message);
}
}

2. Singleton_Pattern.java
class Singleton_Pattern {
public static void main(String[] args) {
Logger L1=Logger.getInstance();
Logger L2=Logger.getInstance();
L1.log("This is the Message from Logger 1");
L2.log("This is the Message from Logger 2");
if(L1==L2)
System.out.println("Both the Logger 1 and Logger 2 are of Same instance");
else
System.out.println("Bother the Logger 1 and Logger 2 are of Different instance");
}
}

Output:

Explanation:
This program is Singleton Design Pattern. I created a Logger class where
only one object can be created using the getInstance() method. In the main()
method, I called getInstance() twice and stored it in L1 and L2. Both refer to the
same Logger object. I used it to log two messages, and at the end, I checked
whether both instances are the same. This ensures that only one instance is
used throughout the program."

You might also like