November 2012
Beginner
336 pages
9h 48m
English
Because design patterns are so abstract, you can expect a lot of variation in the types of questions that are asked.
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.)
Read now
Unlock full access