/memento__caretaker_usage.kt Secret
Created
January 7, 2021 13:03
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UI( | |
private val screen: Screen | |
) { | |
private val editor = Editor() | |
private val backups = mutableListOf<Memento>() | |
fun write(text: String) { | |
backups.add(0, editor.backup()) | |
editor.write(text) | |
editor.render(screen) | |
} | |
fun edit(index: Int, text: String) { | |
backups.add(0, editor.backup()) | |
editor.edit(index, text) | |
editor.render(screen) | |
} | |
fun delete(index: Int) { | |
backups.add(0, editor.backup()) | |
editor.delete(index) | |
editor.render(screen) | |
} | |
fun undo() { | |
val memento = backups.removeAt(0) | |
editor.restore(memento) | |
editor.render(screen) | |
} | |
} | |
fun main() { | |
val screen = StdoutScreen() | |
val ui = UI(screen) | |
with(ui) { | |
write("Hello, there! ") | |
write("How are you? ") | |
write("I hope you feel good :)") | |
edit(1, "Kotlin! ") | |
delete(1) | |
undo() | |
undo() | |
undo() | |
undo() | |
undo() | |
} | |
} | |
/* which produces this: | |
Hello, there! | | |
Hello, there! How are you? | | |
Hello, there! How are you? I hope you feel good :)| | |
Hello, there! Kotlin! |I hope you feel good :) | |
Hello, there! |I hope you feel good :) | |
Hello, there! Kotlin! |I hope you feel good :) | |
Hello, there! How are you? I hope you feel good :)| | |
Hello, there! How are you? | | |
Hello, there! | | |
| | |
/* |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment