Design-Patterns-In-Kotlin
Design-Patterns-In-Kotlin copied to clipboard
Add Prototype pattern
Demonstrate how to implement Prototype pattern in Kotlin
A very simple example:
abstract class Prototype : Cloneable {
public override fun clone() = super.clone() as Prototype
}
class ConcretePrototype1 : Prototype() {
public override fun clone() = super.clone() as ConcretePrototype1
}
object ConcretePrototype2 : Prototype() {
public override fun clone() = super.clone() as ConcretePrototype2
}
fun main() {
val prototype1 = ConcretePrototype1()
println(prototype1.clone())
println(prototype1.clone().clone())
println(ConcretePrototype2.clone())
println(ConcretePrototype2.clone())
}
with the output:
ConcretePrototype1@24d46ca6
ConcretePrototype1@4517d9a3
ConcretePrototype2@372f7a8d
ConcretePrototype2@2f92e0f4
It shows two prototypes: one classic class instance and one object. In the sample, a clone object is also a prototype. Objects may be declared in scala or kotlin, but not yet in java.