Continuing on with my series of design patterns in Scala, here’s an example of the Factory Method pattern. Since this pattern is as OO as you can get, there’s not as major of a difference in approach from languages like Java as there was with some of the other patterns. But as you hopefully have learned to expect, Scala has a few innovations that make the pattern more elegant! These include sealed traits, apply methods, and pattern matching.
The Adapter Pattern is a way to allow one object to be used as another object, usually by creating a wrapper class around the first object which implements the same method or methods. There are various versions. I suppose the correct OO way is to implement the same interface as the other object.
Scala has a powerful language feature called implicit classes that improves the pattern.
I covered the Builder Design Pattern in Java using the example of a form field validator (1, 2, 3). Scala has features that make this pattern obsolete and that’s what this post is about. Continue reading “Learn how Scala makes the builder pattern obsolete”
The Decorator Pattern is one of the most popular design patterns. It is used in places where everyday programmers probably don’t think much about it, like the way streams in Java can wrap each other adding or modifying functionality as needed.
Scala traits are often thought of as just a kind of hybrid of Java interfaces and abstract classes. But actually Scala’s traits and specifically their “stackability” totally kills the decorator pattern. I’ve covered stackable traits before on the blog. Bill Venners covers stackable traits in more detail.
Once you play around with stackable traits, I don’t think you’ll ever think of doing something like the above UML diagram in Scala code. Nevertheless, it’s the only option in other OO languages. In short, good bye decorator pattern. Scala has you beat.
|Class/Method||Type of Collection||Algorithm|
|Arrays.sort||array||timsort (objects) or dual-pivot quicksort (certain primitives)|
If you’re not familiar with the Comparable or Comparator interfaces, now might be the time. As long as your object implements Comparable you can use the above sort methods from the standard library. There are often great uses for Comparator as well, especially when you want multiple ways to sort the same objects. For the rest of the post I’ll deal just with Comparable.