Skip to content

Commit

Permalink
Merge pull request #458 from alanfgn/scala-visitor
Browse files Browse the repository at this point in the history
Adding visitor pattern in scala
  • Loading branch information
ZoranPandovski authored Nov 1, 2022
2 parents fb9f569 + 46d9580 commit f927060
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions Behavioral/Visitor/scala/Visitor.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@

trait Element {
def accept(visitor: Visitor)
}

trait Visitor {

def visitElementA(elementA: ElementA)

def visitElementB(elementB: ElementB)
}


class ElementA extends Element {

override def accept(visitor: Visitor): Unit = {
visitor.visitElementA(this)
}

def featureOfElementA() = "Feature of element A"

}

class ElementB extends Element {

override def accept(visitor: Visitor): Unit = {
visitor.visitElementB(this)
}

def featureOfElementB() = "Feature of element B"

}

class ConcreteVisitorAlpha extends Visitor {

override def visitElementA(elementA: ElementA): Unit = {
println(f"Concrete Visitor Alpha visiting ${elementA.featureOfElementA()}")
}

override def visitElementB(elementB: ElementB): Unit = {
println(f"Concrete Visitor Alpha visiting ${elementB.featureOfElementB()}")
}
}

class ConcreteVisitorBeta extends Visitor {

override def visitElementA(elementA: ElementA): Unit = {
println(f"Concrete Visitor Beta visiting ${elementA.featureOfElementA()}")
}

override def visitElementB(elementB: ElementB): Unit = {
println(f"Concrete Visitor Beta visiting ${elementB.featureOfElementB()}")
}
}


object VisitorPattern {
def main(args: Array[String]): Unit = {
val elements = Seq(new ElementA(), new ElementB())
val visitors = Seq(new ConcreteVisitorAlpha(), new ConcreteVisitorBeta())

elements.foreach(element => {
visitors.foreach(visitor => {
element.accept(visitor)
})
})
}
}

0 comments on commit f927060

Please sign in to comment.