I'm studying Kotlin with design patterns.
So I write a singleton pattern.
Below code is test code. first show that instance is only one. second show that there is no public constructor.
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertSame
import org.junit.jupiter.api.Test
class TestSimpleSingleton {
@Test
fun testCreateSingleton() {
val s = Singleton.Instance()
val s2 = Singleton.Instance()
assertSame(s, s2)
}
@Test
fun testNoPublicConstructors() {
val singleton = Class.forName("Singleton")
val constructors = singleton.constructors
assertEquals(0, constructors.size) // public constructor = 0
}
}
if i use object to implement singleton the test is work well.(val s = Singleton)
object Singleton
but i use a companion object it doesn't work.
class Singleton private constructor(){
companion object {
private var theInstance: Singleton? = null
fun Instance(): Singleton {
if (theInstance == null)
theInstance = Singleton()
return theInstance as Singleton
}
}
}
I write private constructor so I thought it also didn't have any public constructor. but the second test shows that it has one public constructor.
Why did it happen like this?