Singleton with Java

Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.

Use the Singleton pattern when a class in your program should have only a single instance available to all clients; for example, a single database controller accessible by different parts of the program.

Structure

Singleton Design Pattern with Younes Rabdi

Singleton Java Example Code

Lets consider a log file where we want to log activities from multiple threads. We will create a class LogManager which will write data to the log file on the hard drive.

The Difficulty :

Now, if every thread creates a LogManager to write to the file, it will lead to concurrent accesses which can lead to corrupted data or other problems because every LogManager instance will try to access the log file and write data at the same time.

Solution with Singleton :

The singleton pattern will ensure that LogManager Class only has one instance, and will provide a global point of access to it.

The Java Code 

Class : LogsManager (The Singleton)
public final class LogsManager {

    // This attribute will hold the only instance.
    private static LogsManager instance = null;

    // private constructor so not possible to create new instance outside this class.
    private LogsManager() {}

    // The only way to get an instance of LogManager.
    public static LogsManager getInstance() {

        // if the instance is null we will assign a new instance to it and then return it.
        if(instance == null)
            instance = new LogsManager();
        return instance;
    }

    public void addLog(String id, String activityName, String activityValue) {
        // Here we can code a safe way to buffer incoming data and write it to the file when possible.
        // For demo purpose we only will write data to console to keep this simple.
        System.out.println(id.concat(" : ")
                .concat(activityName)
                .concat(" | ")
                .concat(activityValue)
                .concat(" | ")
                .concat(java.util.Calendar.getInstance().getTime().toString()));

    }

}
Class : ConsoleApp (The Client)
public class ConsoleApp {
    public static void main(String[] args) {

        // Now any thread in our app will access the same logsManager.
        LogsManager logsInstance = LogsManager.getInstance();

        // To keep this demo simple we will not create any threads for now. We will see threads in another tutorial.
        logsInstance.addLog("1223", "web browser", "google.com/search");
        // We can also access the addLog function like this
        LogsManager.getInstance().addLog("1223", "web browser", "yahoo.com");

        logsInstance.addLog("5645", "Video Player", "play terminator.mp4");
        logsInstance.addLog("8027", "Visual Studio", "create new Java console project");
    }
}