Last active
April 24, 2022 14:49
-
-
Save kuceraf/8f349f38d32d3f47c41760f6b053dd2b to your computer and use it in GitHub Desktop.
Kotlin Design Pattern: IntrusiveVisitor
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
abstract class Expression { | |
abstract fun print(sb: StringBuilder) | |
} | |
class DoubleExpression(private val value: Double) : Expression() { | |
override fun print(sb: StringBuilder) { | |
sb.append(value) | |
} | |
} | |
class AdditionExpression( | |
private val left: Expression, | |
private val right: Expression | |
) : Expression() { | |
override fun print(sb: StringBuilder) { | |
sb.append("(") | |
left.print(sb) | |
sb.append("+") | |
right.print(sb) | |
sb.append(")") | |
} | |
} | |
fun main() { | |
val expression = AdditionExpression( | |
left = DoubleExpression(1.0), | |
right = AdditionExpression( | |
left = DoubleExpression(2.0), | |
right = DoubleExpression(3.0) | |
) | |
) | |
val sb = StringBuilder() | |
expression.print(sb) | |
println(sb) // (1.0+(2.0+3.0)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment