Singleton in Kotlin - Companion Object and Operator fun invoke
Java Way :
public class Singleton {
private static Singleton INSTANCE = null;
// other instance variables can be here
private Singleton() {};
public static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return(INSTANCE);
}
// other instance methods can follow
}
2.
class Manager private constructor() {
// We do not have static keyword in Kotlin.
// We use Companion Object in Kotlin which is a replacement of static
companion object {
private var instance : Manager? = null
// Already instantiated? - return the instance
// Otherwise instantiate in a thread-safe manner
fun getInstance() = synchronized(this) { // This makes Thread safe
if(instance == null)
instance = Manager()
instance
}
}
}
fun main() {
val m = Manager() -> This cannot be accessed here
Manager.getInstance()
println(Manager.getInstance())
println(Manager.getInstance())
println(Manager.getInstance()) // For all the 3 instances called, only 1 instance is created
}
2.
class Manager private constructor() {
// We do not have static keyword in Kotlin.
// We use Companion Object in Kotlin which is a replacement of static
companion object {
private var instance : Manager? = null
// Already instantiated? - return the instance
// Otherwise instantiate in a thread-safe manner
operator fun invoke() = synchronized(this) { // This makes Thread safeif(instance == null)
instance = Manager()
instance
}
}
}fun main() {Manager() => Manager.invoke() // For all the 3 instances called, only 1 instance is created
}Kotlin Way :object Manager {init{println("Manager Block Initialised")
}
}fun main() {println(Manager)
println(Manager)
}
Comments
Post a Comment