From 275011f836c9394f402b8872a32d917809a50fcd Mon Sep 17 00:00:00 2001 From: Christopher Ng Date: Wed, 16 Oct 2019 21:47:10 +0700 Subject: [PATCH] :sparkles: Introduce Prototype pattern --- README.md | 47 +++++++++++++++++++++++++++ patterns/src/test/kotlin/Prototype.kt | 36 ++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 patterns/src/test/kotlin/Prototype.kt diff --git a/README.md b/README.md index 726d78e..0ffdf0a 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Inspired by [Design-Patterns-In-Swift](https://github.com/ochococo/Design-Patter * [Creational Patterns](#creational) * [Builder / Assembler](#builder--assembler) * [Factory Method](#factory-method) + * [Prototype](#prototype) * [Singleton](#singleton) * [Abstract Factory](#abstract-factory) * [Structural Patterns](#structural) @@ -714,6 +715,52 @@ US currency: USD UK currency: No Currency Code Available ``` +[Prototype](/patterns/src/test/kotlin/Prototype.kt) +------------ + +The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, +creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient. + +#### Example: + +```kotlin +open class Cat : Cloneable { + private var sound = "" + private var species = "" + + init { + sound = "Meow" + species = "Ordinary" + } + + public override fun clone(): Cat = Cat() + + fun powerUp() { + sound = "MEOW!!!" + species = "Super cat" + } +} + +fun makeSuperCat(cat: Cat): Cat = cat.apply { powerUp() } +``` + +#### Usage + +```kotlin +val ordinaryCat = Cat() +val copiedCat = ordinaryCat.clone() +val superCat = makeSuperCat(copiedCat) +println("Copied cat: $copiedCat") +println("Super cat: $superCat") +``` + +#### Output + +``` +Copied cat: Cat@6e1567f1 +Super cat: Cat@6e1567f1 +``` + [Singleton](/patterns/src/test/kotlin/Singleton.kt) ------------ diff --git a/patterns/src/test/kotlin/Prototype.kt b/patterns/src/test/kotlin/Prototype.kt new file mode 100644 index 0000000..f7d96bc --- /dev/null +++ b/patterns/src/test/kotlin/Prototype.kt @@ -0,0 +1,36 @@ +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +open class Cat : Cloneable { + var sound = "" + var species = "" + + init { + sound = "Meow" + species = "Ordinary" + } + + public override fun clone(): Cat = Cat() + + fun powerUp() { + sound = "MEOW!!!" + species = "Super cat" + } +} + +fun makeSuperCat(cat: Cat): Cat = cat.apply { powerUp() } + +class PrototypeTest { + + @Test + fun Prototype() { + val ordinaryCat = Cat() + val copiedCat = ordinaryCat.clone() + + assertEquals(ordinaryCat.sound, copiedCat.sound) + + val superCat = makeSuperCat(copiedCat) + + assertEquals(copiedCat.sound, superCat.sound) + } +}