Sobes.tech
Junior — Middle

Can you give an example of implementing a specific design pattern in practice?

sobes.tech AI

Answer from AI

An example of the Singleton pattern in Java — when you need to ensure that a class has only one instance and provide a global point of access to it:

public class Singleton {
    private static Singleton instance;

    private Singleton() {
        // private constructor prevents external instantiation
    }

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

This pattern is useful, for example, for managing database connections or logging, where a single shared object is needed throughout the application.