Singleton Class in Kotlin and Java: An ultimate Guide Guide
A singleton class is a design pattern that restricts the instantiation of a class to one single instance. This is useful when exactly one object is needed to coordinate actions across a system. Here’s an explanation of the singleton pattern in both Kotlin and Java:
Singleton in Kotlin
Kotlin provides a very straightforward way to create singletons using the object keyword. An object declaration in Kotlin creates a singleton. This approach is thread-safe and guarantees a single instance without any additional synchronization.
Key aspects of Singleton in Kotlin:
object Singleton {
var data: String = "Initial data"
fun showData() {
println(data)
}
}
2.Access:
fun main() {
Singleton.data = "Updated data"
Singleton.showData() // Output: Updated data
}
You can access the singleton directly using its name.
3.Initialization:
The singleton is initialized lazily when it is accessed for the first time.
4.Thread Safety:
Singleton in Java
1.Eager Initialization:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
// Private constructor to prevent instantiation
}
public static Singleton getInstance() {
return INSTANCE;
}
}
2.Lazy Initialization:
public class Singleton {
private static Singleton instance;
private Singleton() {
// Private constructor to prevent instantiation
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
3.Double-Checked Locking:
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// Private constructor to prevent instantiation
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
This method reduces the overhead of acquiring a lock by first checking the instance without synchronization.
4.Bill Pugh Singleton Design:
public class Singleton {
private Singleton() {
// Private constructor to prevent instantiation
}
private static class SingletonHelper {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHelper.INSTANCE;
}
}
This leverages the Java class loader mechanism to ensure the class is loaded only when it is referenced.
5.Enum Singleton:
public enum Singleton {
INSTANCE;
public void showData() {
// Add method implementation
}
}
This is the most straightforward way to implement a singleton in Java. It is thread-safe, serialization-safe, and provides a simple syntax.
No comments: