Design Pattern Problems

Because design patterns are so abstract, you can expect a lot of variation in the types of questions that are asked.

Singleton Implementation

PROBLEM Your application uses a logging class to write debugging messages to the console. How would you implement this logging facility using the Singleton pattern?

The Singleton pattern requires that at most one instance of the logging class exists at any given time. The easiest way to do this is to make the constructor private and initialize the single instance within the class. Here’s a Java implementation of the logger:

// Implements a simple logging class using a singleton.
public class Logger {

    // Create and store the singleton.
    private static final Logger instance = new Logger();

    // Prevent anyone else from creating this class.
    private Logger(){
    }

    // Return the singleton instance.
    public static Logger getInstance() { return instance; }

    // Log a string to the console.
    //
    //   example: Logger.getInstance().log("this is a test");
    //
    public void log( String msg ){
        System.out.println( System.currentTimeMillis() + ": " + msg );
    }
}

If you’ve claimed deep expertise in Java, an interviewer might ask you how an application could create multiple instances of the Logger class despite the existence of the private constructor and how to prevent that from happening. (Hint: think about cloning and object serialization.)

PROBLEM Your application uses a singleton, but it’s not always necessary, and it’s expensive to ...

Get Programming Interviews Exposed: Secrets to Landing Your Next Job, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.