Book Image

Scala Design Patterns

By : Ivan Nikolov
Book Image

Scala Design Patterns

By: Ivan Nikolov

Overview of this book

Scala has become increasingly popular in many different IT sectors. The language is exceptionally feature-rich which helps developers write less code and get faster results. Design patterns make developer’s lives easier by helping them write great software that is easy to maintain, runs efficiently and is valuable to the company or people concerned. You will learn about the various features of Scala and be able to apply well-known, industry-proven design patterns in your work. The book starts off by focusing on some of the most interesting features of Scala while using practical real-world examples. We will also cover the popular "Gang of Four" design patterns and show you how to incorporate functional patterns effectively. By the end of this book, you will have enough knowledge and understanding to quickly assess problems and come up with elegant solutions.
Table of Contents (20 chapters)
Scala Design Patterns
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Preface
Index

The prototype design pattern


The prototype design pattern is a creational design pattern that involves creating objects by cloning them from existing ones. Its purpose is related to performance and keeping it high by trying to avoid expensive calls.

Class diagram

In languages such as Java, we usually see a class that implements an interface with a clone method, which returns a new instance of the class. The following figure shows an example diagram:

In the next section, we will provide a code example of the prototype design pattern from the point of view of Scala.

Code example

The prototype design pattern is really easy to implement in Scala. We can just use one of the language features. Since the prototype design pattern really resembles how cells in biology divide, let's use a cell as an example:

/**
 * Represents a bio cell 
 */
case class Cell(dna: String, proteins: List[String])

In Scala, all case classes have a copy method, which returns a new instance that is cloned from the original one...