Code example

Let's take a look at the code representation for the previous diagram. First of all, we have to define the Node interface through a trait:

trait Node {  def print(prefix: String): Unit}
The prefix parameter in the print method is used to aid visualization when printing the tree to a console.

After we have the interface, we can now define the implementation:

class Leaf(data: String) extends Node {  override def print(prefix: String): Unit =    System.out.println(s"${prefix}${data}")}class Tree extends Node {  private val children = ListBuffer.empty[Node]  override def print(prefix: String): Unit = {    System.out.println(s"${prefix}(")    children.foreach(_.print(s"${prefix}${prefix}"))    System.out.println(s"${prefix})")  }  def add(child: Node): ...

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.