Visitor

The visitor pattern allows us to add new operations to an existing object without modifying it. This pattern is a way to extend functionality and follow the open/closed principle. It's better to try to understand this pattern using a particular example.

The following diagram represents the example that we will touch upon, as follows:

The preceding diagram contains the CarElement interface that is implemented by the Body and Engine classes. The CarElementDriverVisitor class implements the CarElementVisitor interface, which contains an instance of the CarElementVisitor type.

Let's define the CarElement interface:

interface CarElement {
fun accept(visitor: CarElementVisitor)
}

Now, let's define a visitor for this interface:

interface CarElementVisitor {}

We'll add methods to this interface and define two classes that implement the CarElement interface:

class Body : CarElement {
override fun accept(visitor: CarElementVisitor) = visitor.visit(this)
}

class Engine : CarElement {
override fun accept(visitor: CarElementVisitor) = visitor.visit(this)
}

We should add two overloaded versions of the visit method to the CarElementVisitor class:

interface CarElementVisitor {
fun visit(body: Body)
fun visit(engine: Engine)
}

We can now create the Car class, which uses car elements:

class Car : CarElement {

private val elements = arrayOf(Body(), Engine())

override fun accept(visitor: CarElementVisitor) {
elements.forEach { it.accept(visitor) }
}
}

Let's implement the CarElementVisitor interface:

class CarElementDriverVisitor: CarElementVisitor {
override fun visit(body: Body) {
println("Prepare body...")
}

override fun visit(engine: Engine) {
println("Prepare engine...")
}
}

We can use the preceding code as follows:

fun main(args: Array<String>) {
val car = Car()
car.accept(CarElementDriverVisitor())
}

The following is the output:

Prepare body...
Prepare engine...

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.123.106