added Memento design pattern

This commit is contained in:
evitwilly
2022-09-23 08:15:33 +03:00
parent 378d70d3fe
commit 1f7cbc4642
9 changed files with 91 additions and 0 deletions

View File

@ -35,6 +35,7 @@ Content:
* [Observer](/src/main/kotlin/design_patterns/Observer.kt)
* [Dependency Injection](/src/main/kotlin/design_patterns/Dependency%20%20Injection.kt)
* [Adapter](/src/main/kotlin/design_patterns/Adapter.kt)
* [Memento](/src/main/kotlin/design_patterns/Memento.kt)
2. package <code>structures</code> - data structure
* [Binary tree](/src/main/kotlin/structures/BinaryTree.kt)

View File

@ -33,6 +33,7 @@
* [Observer](/src/main/kotlin/design_patterns/Observer.kt)
* [Dependency Injection](/src/main/kotlin/design_patterns/Dependency%20%20Injection.kt)
* [Adapter](/src/main/kotlin/design_patterns/Adapter.kt)
* [Memento](/src/main/kotlin/design_patterns/Memento.kt)
2. пакет <code>ru.structures</code> - структуры данных
* [Бинарное дерево](/src/main/kotlin/structures/BinaryTree.kt)

View File

@ -0,0 +1,55 @@
package design_patterns
/**
*
* pattern: Memento
*
* allows without violating encapsulation, to fix and save the state of an object
* in such a way as to restore it to this state
*
*/
class Bundle(val str: String)
/**
*
* Android system emulating
*
*/
class AndroidSystem {
private var bundle: Bundle = Bundle("")
fun saveBundle(bundle: Bundle) {
this.bundle = bundle
}
fun restoreBundle() = bundle
}
/**
*
* TextView is an Android component that draws text on the screen
*
*/
class TextView1 {
private var text: String = ""
fun setText(text: String) {
this.text = text
}
fun text() = text
fun draw() {
println(text)
}
fun onSaveInstanceState(): Bundle {
return Bundle(text)
}
fun onRestoreInstanceState(bundle: Bundle) {
text = bundle.str
}
}

View File

@ -0,0 +1,34 @@
package design_patterns
import org.junit.Test
import org.junit.jupiter.api.Assertions
class Memento {
@Test
fun test() {
// start Android system
val android = AndroidSystem()
val greetingText = TextView1()
greetingText.setText(greeting)
greetingText.draw()
// rotating Android device (recreating Application components)
// saving state
android.saveBundle(greetingText.onSaveInstanceState())
// the state of the text was lost, but we saved it
greetingText.setText("")
// Android device has already rotated
// restoring state
greetingText.onRestoreInstanceState(android.restoreBundle())
Assertions.assertEquals(greeting, greetingText.text())
}
companion object {
private const val greeting = "Hello, World!"
}
}