Singleton

Java Fundamentals and Patterns

javase
singleton
design-patterns
concepts
What is the Singleton Creational Design-Pattern
Author

albertprofe

Published

Tuesday, June 1, 2021

Modified

Friday, November 1, 2024

1 Definition

The singleton pattern is a design pattern in computer programming and Java that is used to restrict the instantiation of a class to one “single” instance.


This is useful when you want to make sure that only one object of a particular class is created, because this can be helpful for managing resources and ensuring that your program is running as efficiently as possible.

In Java, the singleton pattern can be implemented by creating a private constructor for the class, which prevents other objects from creating instances of the class.

The class also typically provides a static method that allows other classes to access the single instance of the class, which is created the first time the static method is called. This ensures that only one instance of the class is created, and that all other classes can access this instance easily.

Singleton Pattern

Singleton Pattern

2 Example: Logger

Here is an example of a singleton class in Java, using a Logger class as an example:

public class Logger {
    // Private static instance of the class
    private static Logger instance = null;

    // Private instance variable
    private PrintWriter writer;

    // Private constructor
    private Logger() {
        try {
            writer = new PrintWriter("log.txt", "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Public static method for accessing the instance
    public static Logger getInstance() {
        if (instance == null) {
            instance = new Logger();
        }
        return instance;
    }

    // Public method for logging a message
    public void log(String message) {
        writer.println(message);
    }

    // Public method for closing the log file
    public void close() {
        writer.close();
    }
}

In this example, the Logger class defines a Logger() constructor that is private. This means that instances of the Logger class can only be created from within the Logger class itself.

The Logger class also defines a getInstance() method, which is marked as public and static. This method is used to access the instance of the Logger class, and to create the instance if it does not already exist.

Because the Logger class is a singleton, there can only be one instance of the class at any given time. This means that all instances of the Logger class share the same instance of the writer field, which is used to write messages to the log file.

Overall, this example shows how the singleton pattern can be used to implement a Logger class in Java, which ensures that there is only one instance of the Logger class, and provides a global point of access to that instance. This allows the Logger class to manage shared resources, such as the log file, in a more efficient and effective way.

3 Example: ConfigurationManager

Here is another example of a singleton class in Java, using a ConfigurationManager class as an example:

public class ConfigurationManager {
    // Private static instance of the class
    private static ConfigurationManager instance = null;

    // Private instance variables
    private Properties config;

    // Private constructor
    private ConfigurationManager() {
        try {
            config = new Properties();
            config.load(new FileInputStream("config.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Public static method for accessing the instance
    public static ConfigurationManager getInstance() {
        if (instance == null) {
            instance = new ConfigurationManager();
        }
        return instance;
    }

    // Public method for getting a configuration property
    public String getProperty(String key) {
        return config.getProperty(key);
    }
}

In this example, the ConfigurationManager class defines a ConfigurationManager() constructor that is private. This means that instances of the ConfigurationManager class can only be created from within the ConfigurationManager class itself.

The ConfigurationManager class also defines a getInstance() method, which is marked as public and static. This method is used to access the instance of the ConfigurationManager class, and to create the instance if it does not already exist.

Because the ConfigurationManager class is a singleton, there can only be one instance of the class at any given time. This means that all instances of the ConfigurationManager class share the same instance of the config field, which is used to store the configuration properties.

Back to top