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: