An example of a virtual proxy pattern in Kotlin.
Table of contents for design patterns in Kotlin
In place of a complex or heavy object, a skeleton representation may be advantageous in some cases. When an underlying image is huge in size, it may be represented using a virtual proxy object, loading the real object on demand. Wikipedia
Example:
Storage
interface Storage {
fun read(filename: String): String
}
NormalStorage
class NormalStorage : Storage {
override fun read(filename: String) = "Content of file: $filename"
}
SecuredStorage
class VirtualStorage(
private val storageInit: (() -> Storage)
) : Storage {
private val storage: Storage by lazy {
println("Start init")
storageInit().also {
println("End init")
}
}
override fun read(filename: String) = storage.read(filename)
}
Usage:
fun main() {
val normalStorage = NormalStorage()
val virtualStorage = VirtualStorage { NormalStorage() }
println(normalStorage.read("passwords_normal.db"))
println(virtualStorage.read("passwords_virtual_first.db"))
println(virtualStorage.read("passwords_virtual_second.db"))
}
Result
Content of file: passwords_normal.db
Start init
End init
Content of file: passwords_virtual_first.db
Content of file: passwords_virtual_second.db