Singleton Pattern #1: Basics, Definition, Usage

Singleton pattern: As the name suggests, a singleton pattern refers to a pattern where you need only a ’single’ instance of a class to be present. The examples can be windows manager where you want only one window to be active at a time or a file read write where only one method should be updating a file at a time.

Here is a skeleton example of a singleton class:

Public Class singletonExample
{
private static singletonExample instance=null;
private singletonExample{
// no instantiation is possible
}

public static singletonExample getInstance()
{
if (instance==null)
{
instance=new singletonClass();
}
return instance;
}
}

the caller class

public class singletonUser{
singletonExample singletonInstance= singletonExample.getInstance();
}

Explanation:

Here singletonExample is our singleton class. In the first line we have created an instance of this class as null. We have declared a private constructor for the class to make sure that no object of class can be created outside the class.

getInstance() method is the entry point for the class which will return the only instance present for the class. This method is marked as static as it will be called directly from other classes. In this method we check if the instance of singletonExample is already present, if yes, return that instance else create the instance and return it. This makes sure that only one instance of the class is present at any point.

In the user class, that is calling our singleton class, we just need to call our singletonExample.getinstance() method which will return us the instance of singletonExample.

Originally posted February 13, 2007 at 2:10 pm

Brought back using archive.org