Posts Tagged ‘factory method’

Design Patterns in Scala

Posted in Programming, Scala on October 11th, 2013 by Pavel – 44 Comments

Scala puzzleThis article shows how Scala adopts and transforms the classical software design patterns.

The content of the article is also (independently) translated into Russian and Chinese.

Design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished code, but rather a template for how to solve a problem that can be used in many different situations.

Patterns are formalized best practices of effective design, which helps to prevent subtle issues, improve code readability and speed up the development process.

The classical design patterns (mostly, the GoF patterns) are object-oriented. They show relationships and interactions between classes and objects. These patterns are less applicable in pure functional programming (see Haskell’s Typeclassopedia and Scalaz for “functional” design patterns, kind of), however, since Scala is an object-functional hybrid language, these patterns are still very relevant, even in “functional” Scala code.

Sometimes, design patterns may be a sign of some missing feature in a programming language. In such cases, the patterns might be simplified or eliminated when a programming language provides the required features. In Scala, it’s possible to implement most classical design patterns directly, relying on the expressive language syntax.

While Scala may employ additional, language-specific design patterns, this article focuses on the well-known, classical patterns, because these patterns also serve as the means of communication between developers.

Sure we can use the Force all the power of Scala to completely transcend all these patterns, but in this article I intentionally tried to avoid more advanced techniques in favor of more simple and pictorial ones, in order to provide a clean mapping between languages.

Creational patterns:

Structural patterns:

Behavioral patterns:

So, here goes the patterns (all the code is available as a GitHub repository).
Continue reading →