Sobes.tech
Junior — Middle

Can you provide an example of a situation where you used the Singleton pattern in a project?

sobes.tech AI

Answer from AI

The Singleton pattern is used when it is necessary to guarantee that a class has only one instance and to provide a global point of access to it.

An example in Java: in a project for working with application configuration, Singleton can be used so that all parts of the program refer to the same settings object.

public class Configuration {
    private static Configuration instance;
    private Properties props;

    private Configuration() {
        // load settings
        props = new Properties();
        // props.load(...);
    }

    public static synchronized Configuration getInstance() {
        if (instance == null) {
            instance = new Configuration();
        }
        return instance;
    }

    public String getProperty(String key) {
        return props.getProperty(key);
    }
}

Thus, in any part of the code, you can get the settings through Configuration.getInstance() and be sure that the same object is used.

Can you provide an example of a situation where you… - sobes.tech