Of the several patterns out there, the Java Singleton is one of Gangs of Four Design patterns. In many ways it is one of the simplest design patterns to implement, however it does come with some concerns.
The basic idea is that there can be only one object of a given class, and by its design it will restrict the the constructor to ensure only a single instance of the class exists. This means it has some limited uses, but it can be beneficial when used in the right manner.
The constructor is private, but it must have a public method to get the instance.
Uses
Singleton pattern can be used for logging, drivers objects, caching and thread pools.
This pattern can actually be found in some of the core Java classes like RunTime and java.awt.Desktop.
To use it, there is often methods that would be necessary to access it, or provide methods for access.
Singleton Implementation
There are several instances of how to implement the Singleton, however we’re going focus on some of the simpler ones since we’ve not covered threads and other things like that yet.
No matter how we implement our Singleton, there are a few things that remain constant.
- The Constructor is private.
- There is a private static variable of the object.
- There is a public static way to get access to the object – by returning the instance of the object.
Eager Initialization
In this case, the instance is immediately initialized.
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}
public static EagerInitializedSingleton getInstance(){
return instance;
}
}
Notice how you create the instance during the creation of the class as part of the class properties.
Lazy Initialization
Lazy initialization means that your application waits until it is called to create the object. This means its a little faster on startup, but you might have a pause during the runtime of the application
public class LazyInitializedSingleton {
private static LazyInitializedSingleton instance;
private LazyInitializedSingleton(){}
public static LazyInitializedSingleton getInstance(){
if(instance == null){
instance = new LazyInitializedSingleton();
}
return instance;
}
}
Notice how the instance is null until it is called the first time. At that point, a simple if statement checks to see if it is null, and if so, it creates an instance. The nice thing is if the instance is shut down at any time, it is easy to start back up.
The Java Singleton Pattern was originally found on Access 2 Learn