Code example

Now, let's have a look at the previous class diagram from the point of view of Scala code. First, we will focus on the implementation side with the Hasher trait:

trait Hasher {  def hash(data: String): String  protected def getDigest(algorithm: String, data: String) = {    val crypt = MessageDigest.getInstance(algorithm)    crypt.reset()    crypt.update(data.getBytes("UTF-8"))    crypt  }}

Then, we have three classes that implement it—Md5Hasher, Sha1Hasher, and Sha256Hasher. Their code is pretty simple and similar, but yields different results:

class Sha1Hasher extends Hasher {  override def hash(data: String): String =     new String(Hex.encodeHex(getDigest("SHA-1", data).digest()))}class Sha256Hasher extends Hasher {  override def hash(data:  ...

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.