Morgan Stanley Interview Question
A singleton is an object-oriented design pattern in which only one instance of the class can be instantiated at a given time. An example would include a class that handles the printer queue. Instead of creating a new instance of the class, you would call a class function to retrieve the current instance of the class.
An example of this in Java:
public class MySingleton
{
// reference to current instance
private static MySingleton instance = null;
// making the constructor private ensures only we can call this
private MySingleton()
{
// do stuff
}
// the synchronized keyword makes it thread safe
public static synchronized getInstance()
{
if(instance == null)
{
instance = new MySingleton();
}
return instance;
}
}
Application code would use the MySingleton class like this:
MySingleton singleton = MySingleton.getInstance();
A class whose number of instances that can be instantiated is limited to one is called a singleton class. Thus, at any given time only one instance can exist, no more.
- Anonymous November 23, 2010