Pages

Showing posts with label trait. Show all posts
Showing posts with label trait. Show all posts

Sunday, September 7, 2014

HowTo:: Design patterns with Scala: GoF Structural Pattern Adapter and power of Trait

  
Img.1.:: Parts of Adapter patterns

   In this example I want to show power of trait usage in 2 different ways of Adapter Structural pattern implementations. There are couple of reasons why could be worth to think about the Adapter pattern. Basically the intent is to convert interface of the one type into the interface that client expects to use.
Pattern can be divided into the following parts (Img.1.):
1. Client - is an object that requires functionality provided by Adaptee but it's exposed by Adapter
2. Adapter - is an object that converts the interface expected by the client into the interface provided by Adaptee 
3. Adaptee - is an object that provides the implementation and the interface invoked by the Adapter

in both Adapter examples we do use same Client implementation: 
class Client(service: Service) {
  def doWork = {
    service.invoke
  }
}
and Service trait which defines method process:
trait Service {
  def process(): Unit
}
  Already from the Main Scala Object AdapterTest.scala is noticeable the 1st warm up of the Scala trait power which will be fully exposed by AdaptorTrait latter.
object AdapterTest {

  private val logger = LoggerFactory.getLogger(getClass)

  def main(args: Array[String]) ={
    logger.debug("Test Adapter pattern")
    val adaptor = new AdaptorOne
    val clientWithoutTrait = new Client(adaptor)
    clientWithoutTrait.doWork()

    val adaptorTraitOne = new AdapteeOne with AdaptorTrait
    val adaptorTraitTwo = new AdapteeTwo with AdaptorTrait
    val clientWithTrait1 = new Client(adaptorTraitOne)
    clientWithTrait1.doWork()

    val clientWithTrait2 = new Client(adaptorTraitTwo)
    clientWithTrait2.doWork()
  }

}

1. Object based implementation without trait we do use classical scala class definition of the AdapteeOne that provides implementation to the action() that Client wants.
class AdapteeOne extends Adaptee{
  private val logger = LoggerFactory.getLogger(getClass)
  def action() = { logger.debug("Adaptee One Action One")}
}
  The Adapee trait is used to make code standardised and also to point out limits of the presented Object implementation .
trait Adaptee {
  def action()
}
  Currently has been implemented 1st part of the blog post -> Adapter in the classical object way.

2. trait based approach is inspired by having two, almost same, objects (example: CAR1, CAR2) and both has different implementation of the action() function (example: both cars can ride). We again use AdapteeOne (previously implemented) and we create AdapteeTwo scala class.
class AdapteeTwo extends Adaptee{
  private val logger = LoggerFactory.getLogger(getClass)
  def action() = { logger.debug("Adaptee Two Action")}
}
   Both classes extend Adaptee trait which method is served to the AdaptorTrait that extend the Service (also previously defined)
trait AdaptorTrait extends Service{
  self: Adaptee =>
  def process() = action()
}
   Now we are ready also with 2nd Adapter pattern example usage. Trait usage (AdaptorTrait) allows to be mixed into a type either directly at the type declaration time or an object creation time.  This simply allows latter object behaviour extension. 
Traits go ahead! implementation with them is much easier, readable and extendable  + testable, less code

Thursday, August 14, 2014

Design Patterns with Scala: GoF Creational Pattern - Factory Operation (GoF: Factory)

  Factory operation design pattern provides the way how to construct object of the specific type. The intent is to hide an object instantiation from a client which support flexibility in such instantiation process (decide which class will be instantiated).
  Let's show over the simple example how such Factory method deals with the issue of the different type of object creation

  UnivProduct trait is the abstract super type of objects which will be produced by object ProductFactory.
trait UnivProduct {
  val name: String
  val value: Any
}
  By having defined abstraction UnivProduct we can create two concrete classes which can be instantiated by object ProductFactory latter.
UnivProductOne:
case class UnivProductOne(i: Int) extends UnivProduct{
  val name:String = "MyIntegerProduct"
  val value:Int = i

  override def toString = "name= "+ name +" val= " + value
}
  UnivProductTwo:
case class UnivProductTwo(s: String) extends UnivProduct {
  val name:String = "MyStringProduct"
  val value:String = s

  override def toString = "name= "+ name +" val= " + value
}
  Now we create FactoryOperation trait which provides us the specification of the methods (behaviour) that ProductFactory object must provide.
trait FactoryOperation {
  def create(a: Any): UnivProduct
}
  Then we define ProductFactory object in following way:
object ProductFactory extends FactoryOperation{
  implicit def create(a: Any): UnivProduct = a match {
    case s: String => UnivProductTwo(s)
    case i: Int => UnivProductOne(i)
  }
}
which simplifies the access to the Factory with limiting ability to employ different Product Factories (can by fixed by implementing factory of factories). The methods create in ProductFactory object is marked as implicit (inserted by compiler).
  At the end we create the singleton Scala object FactoryTest to put all together and see the result.
object FactoryTest {
  private val logger = LoggerFactory.getLogger(getClass)

  def main(args: Array[String]): Unit = {
    val productA: UnivProduct = ProductFactory.create("Mirage")
    logger.debug("ProductA name= " + productA.name + " value= " + productA.value)
    logger.debug("ProductA toString= " + productA)

    val productB:UnivProduct = ProductFactory.create(22)
    logger.debug("ProductB name= " + productB.name + " value= " + productB.value)
    logger.debug("ProductB toString= " + productB)

    val productC: UnivProduct = "Tanja"
    logger.debug("ProductC name= " + productC.name + " value= " + productC.value)
    logger.debug("ProductC toString= " + productC)

    val productD: UnivProduct = 5
    logger.debug("ProductD name= " + productD.name + " value= " + productD.value)
    logger.debug("ProductD toString= " + productD)
  }
}

expected output:
ProductA name= MyStringProduct value= Mirage
ProductA toString= name= MyStringProduct val= Mirage
ProductB name= MyIntegerProduct value= 22
ProductB toString= name= MyIntegerProduct val= 22
ProductC name= MyStringProduct value= Tanja
ProductC toString= name= MyStringProduct val= Tanja
ProductD name= MyIntegerProduct value= 5
ProductD toString= name= MyIntegerProduct val= 5
  Enjoy using Factory Operation Design patter and my GiTHub is still in progress as I want to much more to share.

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.