Skip to content

Add Prototype pattern #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
------------

Expand Down
36 changes: 36 additions & 0 deletions patterns/src/test/kotlin/Prototype.kt
Original file line number Diff line number Diff line change
@@ -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)
}
}