Design-Patterns-In-Kotlin icon indicating copy to clipboard operation
Design-Patterns-In-Kotlin copied to clipboard

Add Prototype pattern

Open babedev opened this issue 4 years ago • 1 comments

Demonstrate how to implement Prototype pattern in Kotlin

babedev avatar Oct 16 '19 14:10 babedev

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.

jolkdarr avatar Nov 30 '19 18:11 jolkdarr