Singleton Design Pattern - Step by step Guide
Tags: design, designpatterns, java, programming
Published: 2023-10-14 18:09:52

**Singleton Design Pattern - The One-and-Only Pattern:**

The Singleton Design Pattern is like a rule for creating a unique, one-of-a-kind object in your software. It ensures that there's only one instance (object) of a particular class in your entire program. It's a bit like having a special key that opens a unique door, and no matter how many times you use that key, it always opens the same door.

**When Do We Use It?**

Imagine you have a program, and you want to make sure that there's only one "boss" or one "manager" in charge of a certain task. The Singleton pattern helps you create this single manager.

**For Examples**:

1. **Database Connection Pool:**
   In a multi-threaded application, you might want to ensure that there's only one pool of database connections shared across all parts of your application. This way, you prevent multiple, costly database connections from being created.

2. **Logging Service:**
   When logging events or errors in your application, you typically want all components to write to the same log file. A Singleton Logger ensures that all parts of your code log to a single, consistent log file.

3. **Configuration Manager:**
   To manage application settings or configurations, you can use a Singleton Configuration Manager. This ensures that all parts of your code access and modify the same set of configurations.

In all these cases, the Singleton pattern guarantees that there's only one instance of the manager, service, or resource, and it's shared across the entire application, ensuring consistency, reducing resource consumption, and simplifying management.

**How to create Singletons - Step by step guide**
We will create a simple Logging Singleton as below:

We will create a simple Logging Singleton as below

**Step 1: Define the Singleton Class**
In Java, we create a class called Logger to manage logging throughout our application.
**Step 2: Private Constructor**
We make sure that no one from the outside can create a new Logger whenever they want. To do this, we use a private constructor. It's like having a secret entrance that only the class itself can use.
**Step 3: Static Instance and getInstance() Method**
The magic of the Singleton pattern happens here. We create a method called getInstance() that checks if the Logger has already been created. If it has, we give you that same Logger back. If not, we create it and give it to you. It's like having one special key to a secret room, and you can't have more than one.
**Step 4: Logging Method**
Inside our Logger class, we have a method called log. This is where you can tell the Logger to log messages. In this example, we just print the messages to the screen, but you can make it do fancier things like write to a file or send logs to a server.

```java
public class Logger {
    // Private static instance for the Logger
    private static Logger instance;

    // Private constructor to prevent external instantiation
    private Logger() {
        // Initialize your logger here (e.g., open a log file or set configurations)
    }

    // Public method to access the Singleton instance
    public static Logger getInstance() {
        if (instance == null) {
            instance = new Logger();
        }
        return instance;
    }

    // Public method to log messages
    public void log(String message) {
        // Log the message (you can define how and where to log here)
        System.out.println("Log: " + message);
    }
}
```

**Step 5: Using the Logger**
Now, when you want to use the Logger in your program, you can get it using the getInstance() method. It's like using that special key to access the Singleton Logger. Then, you can use the log method to log messages, and all those messages will go through the same Logger, making your application's logging consistent.
Like in below example, both log messages will use the same Logger instance.

```java
public class Application {
    public static void main(String[] args) {
        // Get the Logger instance
        Logger logger = Logger.getInstance();

        // Log messages
        logger.log("This is a log message.");

        // Get the Logger instance
        Logger anotherLogger = Logger.getInstance();

        // Log messages
        anotherLogger.log("Another log message.");
    }
}
```

😍 If you enjoy the content, please 👍 like, 🔄 share, and 👣 follow for more updates!