24
Head First Design Pattern: 4 of 10
I just learnt my fourth design from the Head First Design Pattern book. Today, I learnt about the Singleton pattern.
According to Head First Design Patterns, the Singleton pattern is a pattern that is used to ensure a class has only one instance, and provides a global point of access to it.
For example, the singleton pattern can be implemented in Java like this
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
In order to ensure the
Singleton
class only has one instance, It's constructor is marked as private. Singleton
has an API called getInstance()
. The Singleton pattern seems like a very simple pattern but there are some gotchas you need to be aware of when it comes to using the Singleton pattern and multithreading. In a multithreaded code, it is possible to create multiple instances of the class above since multiple thread can have access to the
There are many ways to fix this:
getInstance
function at the same time.There are many ways to fix this:
1: Refactor the code above to use synchronised keyword.
public class Singleton {
private volatile static Singleton instance;
private Singleton() {
}
public static synchronised Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
By adding the synchronised keyboard to the
getInstance()
we are forcing every thread to wait it's turn before they enter the function. So only one thread can access the getInstance()
function.2: Simply use the
Object
keyword from Kotlin. Kotlin has the Singleton pattern built into the language with the Object
keyword.object Singleton {
}
If you need to have on instance of a class, for example, loggers, analytics, crash reporting. You should use the Singleton pattern