Singleton Design Pattern
Pattern: The Singleton is a creational design pattern that lets you ensure that a class has only one instance while providing a global access point to this instance.
The most common way to implement the pattern follows:
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() { /* The constructor is not visible! */ }
public static Singleton getInstance() {
return INSTANCE;
}
}
The code above provides the following pattern:
- Make the default constructor private, to prevent other objects from using the
new
operator with the Singleton class. - Create a
static
creation method that acts as a constructor.
Singleton design pattern is used in core Java classes, for example java.lang.Runtime
. The documentation of the Runtime
class states: "Every Java application has a single instance of class Runtime
that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime
method."
Here is an example of using the Runtime
class:
/**
* Runtime class can be used to get the memory used by a Java application.
*/
public class RuntimeDemo {
private static final long KB = 1024;
public static void main(String[] args) {
// Note I'm not using Runtime runtime = new Runtime();
Runtime runtime = Runtime.getRuntime();
long startMemory, endMemory, netMemory;
startMemory = runtime.totalMemory() - runtime.freeMemory()
// run some application
endMemory = runtime.totalMemory() - runtime.freeMemory();
netMemory = endMemory - startMemeory;
System.out.printf("Application used %d kb memory.\n",
netMemory / KB);
}
}
The Runtime.getRuntime();
is similar to the Singleton.getInstance();
.
When to use this pattern? Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program; a single logging object, hardware drivers' objects, etc.
Advantage: You can be sure that a class has only a single instance. Moreover, you gain a global access point to that instance.1
1 Unlike global variables that are unsafe (since any code can potentially overwrite the contents of those variables and crash the app), the Singleton pattern lets you safely access some object from anywhere in the program; it protects the single instance from being overwritten by other code.