Lazy Initialization:-The instantiation of an object can be delayed until it is actually needed.
Usage: This especially beneficial when the constructor is doing a costly job like, accessing a remote database.
Example:
This code demonstrates how the Singleton pattern can be used to create a counter to provide unique sequential numbers, such as might be required for use as primary keys in a
Database:
Sequence.java
public class Sequence {
private static Sequence instance;
private static int counter;
private Sequence()
{
counter = 0; // May be necessary to obtain
// starting value elsewhere...
}
public static synchronized Sequence getInstance()
{
if(instance==null) // Lazy instantiation
{
instance = new Sequence();
}
return instance;
}
public static synchronized int getNext()
{
return ++counter;
}
}
Some things to note about this implementation:
- Synchronized methods are used to ensure that the class is thread-safe.
- This class cannot be subclassed because the constructor is private. This may or may not be a good thing depending on the resource being protected. To allow subclassing, the visibility of the constructor should be changed to protected.
- Object serialization can cause problems; if a Singleton is serialized and then deserialized more than once, there will be multiple objects and not a singleton