Skip to content

Instantly share code, notes, and snippets.

@DHosseiny
Created October 19, 2023 13:59
Show Gist options
  • Save DHosseiny/55f8c11d5c3f451c9a122d628903ef2d to your computer and use it in GitHub Desktop.
Save DHosseiny/55f8c11d5c3f451c9a122d628903ef2d to your computer and use it in GitHub Desktop.
visitors
sealed interface Item {
val weight: Int
val stringRepresentation: String
}
class Box(override val weight: Int) : Item {
override val stringRepresentation: String = "Box"
}
class Container(items: List<Item>) : Item {
override val weight: Int = items.sumOf { it.weight } + 2
// or ==> override val weight: Int
// get() = items.sumOf { it.weight } + 2
override val stringRepresentation: String = "Container"
}
class WeightCalculator {
fun calculate(items: List<Item>) = items.sumOf { it.weight }
}
class PrettyPrinter(private val logger: Logger) {
init {
logger.config(Level.VERBOSE)
}
fun print(items: List<Item>) = items.forEach { logger.log(it.stringRepresentation) }
}
class XMLPrinter(private val xmlWriter: XMLWriter) {
fun print(items: List<Item>) {
xmlWriter.writeComment("writing all items")
items.forEach {
xmlWriter.addNode(it.stringRepresentation) // representing xml in parent-child format is inhibited for brevity
}
xmlWriter.writeComment("finish writing items")
}
}
class XMLWriter {
fun addNode(stringRepresentation: String) {
TODO("Not yet implemented")
}
fun writeComment(s: String) {
TODO("Not yet implemented")
}
}
class Logger {
fun config(level: Level) {
TODO("Not yet implemented")
}
fun log(stringRepresentation: String) {
TODO("Not yet implemented")
}
}
enum class Level {
VERBOSE
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment