Table of content

Visitor Pattern in Kotlin

The Visitor pattern is used when we have to perform an operation on a group of similar kind of Objects.

With the help of the visitor pattern, we can move the operational logic from the objects to another class.

package behavioral
interface PlanetVisitor {
    fun visit(planet: PlanetAlderaan)
    fun visit(planet: PlanetCoruscant)
    fun visit(planet: PlanetTatooine)
    fun visit(planet: MoonJedah)
}
interface Planet {
    fun accept(visitor: PlanetVisitor)
}
class MoonJedah : Planet {
    override fun accept(visitor: PlanetVisitor) = visitor.visit(planet = this)
}
class PlanetAlderaan : Planet {
    override fun accept(visitor: PlanetVisitor) = visitor.visit(planet = this)
}
class PlanetCoruscant : Planet {
    override fun accept(visitor: PlanetVisitor) = visitor.visit(planet = this)
}
class PlanetTatooine : Planet {
    override fun accept(visitor: PlanetVisitor) = visitor.visit(planet = this)
}
class NameVisitor(var name: String = "") : PlanetVisitor {
    override fun visit(planet: PlanetAlderaan) {
        name = "Alderaan"
    }
    override fun visit(planet: PlanetCoruscant) {
        name = "Coruscant"
    }
    override fun visit(planet: PlanetTatooine) {
        name = "Tatooine"
    }
    override fun visit(planet: MoonJedah) {
        name = "Jedah"
    }
}
fun main(args: Array<String>) {
    val planets = mutableListOf(PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedah())
    val visitor = NameVisitor()
    planets.forEach {
        it.accept(visitor)
        println(visitor.name)
    }
}
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions