Code example

Now, let's have a look at the actual code that describes the decorator design pattern shown in the previous diagram. First of all, we define our InputReader interface using a trait:

trait InputReader {  def readLines(): Stream[String]}

Then, we provide the basic implementation of the interface in the AdvancedInputReader class:

class AdvancedInputReader(reader: BufferedReader) extends InputReader {  override def readLines(): Stream[String] =    reader.lines().iterator().asScala.toStream}

In order to apply the decorator design pattern, we have to create different decorators. We have a base decorator that looks as follows:

abstract class InputReaderDecorator(inputReader: InputReader) extends InputReader {  override def readLines(): 

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.