Sobes.tech
Junior — Middle

Can you give an example of implementing the Singleton pattern in code?

sobes.tech AI

Answer from AI

The Singleton pattern guarantees that a class has only one instance and provides a global point of access to it.

Example of Singleton implementation in Android (Java):

public class Singleton {
    private static Singleton instance;

    private Singleton() {
        // private constructor to prevent external instantiation
    }

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

Here, the getInstance() method creates the object on the first call and returns it on subsequent calls. The synchronized keyword ensures thread safety in multithreaded access.