What's a Singleton? A commonly asked question. A
Singleton is a class for which only one instance can exist within a program ie. only one single object of that particular class can be created in a program.
Write a class in a way which prevents a casual programmer from creating more than one instance. Have a constructor, but make it private so that no other classes may call it. Now that we have no constructor, we need to make a way for people to create a single instance of the class. Typically this is done by provding a static method which creates an instance, but will create only one. If it is called again, it just returns the same instance that it created the first time.
The last thing to remember is that Java is a multi-threaded language in which many things can be happening "at once". If two threads were to call getInstance at the same time, then our class might occasionally create two instances, which would be wrong and very hard to test. So we make use of
Java's built-in synchronization mechanism to make sure that only one thread can call getInstance at any one time.
Here's the code:
public class SimpleSingleton
{
private static SimpleSingleton instance = null;
private SimpleSingleton() {}
public synchronized static SimpleSingleton getInstance()
{
if (instance == null)
{
instance = new SimpleSingleton();
}
return instance;
}
public void callMethod()
{
System.out.println("Calling it's method");
}
public static void main(String[] args)
{
SimpleSingleton.getInstance().callMethod();
}
}
Thanks to
JavaRanch for the tip.
Technorati Tags: What's a Singleton?, Singleton
Blogs linking to this article