Intro to singletons
When applying the singleton pattern we are aiming to create only one instance of a class in memory of the application.
Singleton pattern makes sure that:
- only one instance of a class is in the application
- there is one point of access to this object within the application
Singleton:
- Singletons are obtained as a private static variable within their class.
- We access the object by calling a static method.
- A singleton’s constructor is private.
Creation and Compilation
We can instantiate a singleton object when we define the instance reference. Or we create it using a static initialisation block that is executed when the class is loaded.
Examples
Instantiate when declared
class SingletonA{
private static SingletonA ob = new SingletonA();
private SingletonA(){}
public static synchronized SingletonA getInstance() {
return ob;
}
}
Instantiate with static block
class SingletonB {
private static SingletonB ob;
private SingletonB(){}
static {
ob = new SingletonB();
}
public static synchronized SingletonB getInstance() {
return ob;
}
}
Compilation
What do you think you will see when you compare the structure of the compiled .class files of InstanceA.java and InstanceB.java ?
There is nothing to compare! Both .class files have exactly the same structure:
class SingletonA {
private static SingletonA ob = new SingletonA();
private SingletonA() {
}
public static synchronized SingletonA getInstance() {
return ob;
}
}
class SingletonB {
private static SingletonB ob = new SingletonB();
private SingletonB() {
}
public static synchronized SingletonB getInstance() {
return ob;
}
}