Tuesday, August 12, 2014

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.

No comments: