Skip to content

Instantly share code, notes, and snippets.

@fiddlerwoaroof
Last active June 13, 2019 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fiddlerwoaroof/b24b321ddcfb11470241326e4dd7552d to your computer and use it in GitHub Desktop.
Save fiddlerwoaroof/b24b321ddcfb11470241326e4dd7552d to your computer and use it in GitHub Desktop.
import java.lang.RuntimeException
import java.util.Arrays
object VariantWorld2 {
class Greet : World.Visitor {
fun visit(subject: Dog, arg: String): String {
return "$arg is greeted"
}
fun visit(subject: Cat, arg: String): String {
return "$arg is greeted"
}
override fun visit(subject: World.Subject, arg: String): String {
if (subject is Dog) {
return subject.receive(this, arg)
} else if (subject is Cat) {
return subject.receive(this, arg)
}
throw RuntimeException();
}
}
class Dog(name: String) : World.Animal(name) {
fun receive(visitor: Greet, arg: String): String {
return visitor.visit(this, this.name + ": Joyfully " + arg)
}
fun receive(visitor: Leave, arg: String): String {
return visitor.visit(this, this.name + ": Sadly " + arg)
}
}
class Cat(name: String) : World.Animal(name) {
fun receive(visitor: Greet, arg: String): String {
return visitor.visit(this, this.name + ": Sadly " + arg)
}
fun receive(visitor: Leave, arg: String): String {
return visitor.visit(this, this.name + ": Joyfully " + arg)
}
}
class Leave : World.Visitor {
fun visit(subject: Dog, arg: String): String {
return "$arg is left"
}
fun visit(subject: Cat, arg: String): String {
return "$arg is left"
}
override fun visit(subject: World.Subject, arg: String): String {
if (subject is Dog) {
return subject.receive(this, arg)
} else if (subject is Cat) {
return subject.receive(this, arg)
}
throw RuntimeException();
}
}
@JvmStatic
fun main(args: Array<String>) {
val fido = Dog("Fido")
val garfield = Cat("Garfield")
val greet = Greet()
val leave = Leave()
for (a in Arrays.asList(fido, garfield)) {
for (v in Arrays.asList(greet, leave)) {
System.out.println(v.visit(a, "bob"))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment