Pages

Tuesday, August 12, 2014

Design Patterns with Scala: Fundamental Pattern - Marker Trait

The Marker Trait pattern is the fundamental pattern in Scala. The main point is in using trait which are free on any declaration (method, function etc.) to indicated additional type logical semantic within the domain. The Marker Trait pattern adds ability to be treated as part of Scala type system. For example such approach is used in scala.Mutable or scala.Immutable traits to distinguish between them to indicate the semantic.

In the example we define trait MarkerTrait which will be mixed into any other classes
trait MarkerTrait {
}
Then we define two example classes with some methods.
ClassOne:
case class ClassOne(id: String) extends MarkerTrait{
  def name: String = "ClassOne ID= " + id
}
and ClassTwo:
case class ClassTwo(value: String) extends MarkerTrait{
  def name: String = "ClassTwo value= " + value
}

After having defined classes we define the universal printer UnivPrinter object (note: is singleton) with methods print where MarkerTrait can be passed and printed out.
object UnivPrinter {
  private val logger = LoggerFactory.getLogger(getClass)
  def print(o: MarkerTrait) = {
    logger.debug("MarkerTrait " + o)
  }
}
As the last step we can define object MarkerTest with main method. Inside the main method we instantiate our two classes (ClassOne, ClassTwo) and pass them to the UnivPrinter.print method
object MarkerTest {
  private val logger = LoggerFactory.getLogger(getClass)
  def main(args: Array[String]): Unit = {
    logger.debug("Marker Trait Fundamental Pattern")
    UnivPrinter.print(new ClassOne("ID"))
    UnivPrinter.print(new ClassTwo("Value"))
  }
}
As the alternative connection to the Java world can be taken Annotation. The Annotation is not part of the Scala type system. The trait itself is much powerful in Scala then interfaces in Java as trait can define additional behaviour. This trait power can cause some implementation mixing issues.


No comments: