Code example

Let's take a step-by-step look at the code that implements the visitor design pattern for the previous example. First of all, we have our model of the document and all the elements that can build it:

abstract class Element(val text: String) {  def accept(visitor: Visitor)}class Title(text: String) extends Element(text) {  override def accept(visitor: Visitor): Unit = {    visitor.visit(this)  }}class Text(text: String) extends Element(text) {  override def accept(visitor: Visitor): Unit = {    visitor.visit(this)  }}class Hyperlink(text: String, val url: String) extends Element(text) {  override def accept(visitor: Visitor): Unit = {    visitor.visit(this)  }}class Document(parts: List[Element]) {  def accept(visitor: Visitor): Unit = { parts.foreach(p ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.