WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Design Patterns · Basic · question 4 of 100

What is the Singleton pattern, and when would you use it?

📕 Buy this interview preparation book: 100 Design Patterns questions & answers — PDF + EPUB for $5

Singleton is a creational design pattern that allows ensuring that only one instance of a class is created, while providing a global point of access to this object.

The Singleton pattern can be useful in several scenarios where you need to ensure that certain objects are created only once within an application, and that these objects are accessible to every part of the application that needs to use them.

Here are a few cases where Singleton pattern can be helpful:

- When you need to maintain a single point of control over a specific resource or service, e.g. a database connection, a thread pool, or a logging service. - When you want to ensure that there is only one instance of a particular object, e.g. a configuration manager, a cache manager, or a registry.

In general, Singleton pattern is a great choice when you have a class that needs to provide a consistent interface across multiple components of the system, and you want to ensure that all of these components use the same instance of the class.

Here’s a basic implementation of the Singleton pattern in Java:

public class Singleton {
  private static Singleton instance;

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

  // global access point to the Singleton instance
  public static Singleton getInstance() {
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
}

In this example, the Singleton class contains a private constructor to prevent direct instantiation, and a static getInstance() method that returns the single instance of the class. The first time the getInstance() method is called, the Singleton object is instantiated and stored in the instance variable. On subsequent calls, the existing Singleton object is returned.

One potential issue with this implementation is that it is not thread-safe, meaning that it could lead to multiple instances of the Singleton being created if multiple threads try to call getInstance() at the same time. To make the pattern thread-safe, the getInstance() method should be synchronized or use double-check locking.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Design Patterns interview — then scores it.
📞 Practice Design Patterns — free 15 min
📕 Buy this interview preparation book: 100 Design Patterns questions & answers — PDF + EPUB for $5

All 100 Design Patterns questions · All topics