Visitor Pattern in Kotlin

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

With the help of 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)
    }
}		

About Author

This article is written by Pavan, who is serving notice period in an MNC, Bangalore. He thought, let the articles speak rather than his image. He is also the same person who created the reporter for Protractor Jasmine

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions