forked from dbacinski/Design-Patterns-In-Kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Memento.kt
53 lines (40 loc) · 1.33 KB
/
Memento.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
data class Memento(val state: String)
class Originator(var state: String) {
fun createMemento(): Memento {
return Memento(state)
}
fun restore(memento: Memento) {
state = memento.state
}
}
class CareTaker {
private val mementoList = ArrayList<Memento>()
fun saveState(state: Memento) {
mementoList.add(state)
}
fun restore(index: Int): Memento {
return mementoList[index]
}
}
class MementoTest {
@Test
fun Memento() {
val originator = Originator("initial state")
val careTaker = CareTaker()
careTaker.saveState(originator.createMemento())
originator.state = "State #1"
originator.state = "State #2"
careTaker.saveState(originator.createMemento())
originator.state = "State #3"
println("Current State: " + originator.state)
assertThat(originator.state).isEqualTo("State #3")
originator.restore(careTaker.restore(1))
println("Second saved state: " + originator.state)
assertThat(originator.state).isEqualTo("State #2")
originator.restore(careTaker.restore(0))
println("First saved state: " + originator.state)
assertThat(originator.state).isEqualTo("initial state")
}
}