Pages

Showing posts with label singleton. Show all posts
Showing posts with label singleton. Show all posts

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.


Design Patterns with Scala: Creational Pattern - Singleton

  The singleton design pattern is probably most known one from GoF Creational Pattern list. The singleton pattern says that only one instance of the specific class will be ever created per ClassLoader. 
ps: "This is little bit different in Spring Framework. The Spring Singleton is unique per Spring IoC container per bean which means single instance per Spring context. It also means it's not the singleton pattern" (note) 

  In Java is quite easy to create Singleton pattern and as the whole world is Multi-Threading I'd recommend to reflect this fact and use any of thread-safe implementation double-check-locking or volatile keyword (value is taken then from the main memory and follows happens-before relationship on visibility of among multiple threads). 
The initialisation process is necessary only when the instance is created (by calling getInstance() method). 

In Scala is situation less complicated because in Scala there are no static members (ps: static members concept in Java goes a bit against the OOP principle where everything is an object). Scala has singleton objects done by usage of keyword object
object Singleton {
  val id = "singleton"
  override def toString = "this is the Singleton object"
}
The example shows how easy it is to achieve the singleton pattern is in Scala.
More patterns are on the way and they will be soon on my github soon.