0% found this document useful (0 votes)
25 views3 pages

Singleton Pattern

The document describes the implementation of the Singleton design pattern for a logging utility class. It outlines the steps to create a Logger class that ensures only one instance exists throughout the application, along with a sample code implementation. The main function demonstrates the usage of the Logger instance and verifies that the same instance is used across multiple calls.

Uploaded by

moghana1025
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)
25 views3 pages

Singleton Pattern

The document describes the implementation of the Singleton design pattern for a logging utility class. It outlines the steps to create a Logger class that ensures only one instance exists throughout the application, along with a sample code implementation. The main function demonstrates the usage of the Logger instance and verifies that the same instance is used across multiple calls.

Uploaded by

moghana1025
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

Design Patterns and Principles

Exercise 1: Implementing the Singleton Pattern

Scenario:

You need to ensure that a logging utility class in your application has only one instance
throughout the application lifecycle to ensure consistent logging.

Algorithm:
1. Define Logger class with a private static instance and private constructor.

2. In constructor, print "Logger created" to show it’s called only once.

3. Implement getInstance() to return the single instance of Logger.

4. If instance is null, create it; else return existing instance.

5. Add log(String message) to print the given log message.

6. In Main, get logger instance 3 times and log different messages.

7. Compare all logger references; if equal, print "Same Logger used everywhere."

Code:

[Link]
package mylogger;

public class Logger {

private static Logger instance;

private Logger() {

[Link]("Logger created");

public static Logger getInstance() {

if (instance == null) {

instance = new Logger();

}
return instance;

public void log(String message) {

[Link](message);

[Link]

package mylogger;

public class Main {

public static void main(String[] args) {

Logger loggerA = [Link]();

[Link]("User clicked login.");

Logger loggerB = [Link]();

[Link]("Fetching user data...");

Logger loggerC = [Link]();

[Link]("User logged out.");

if (loggerA == loggerB && loggerB == loggerC) {

[Link]("Same Logger used everywhere.");

OUTPUT:

You might also like