O'Reilly logo

Scala Design Patterns - Second Edition by Ivan Nikolov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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(): 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required