Singleton class made easy in Scala

Singleton

Singleton is a notorious OOPs design pattern, which allows only one instance of the class to be created at any point of time. This is used primarily for heavy weight classes that are not supposed to be created for every instantiation request.

Private constructor (Ingredient #1)

To make the class singleton the key ingredient is Private Constructor in the class. Since private constructor is not accessible from outside of the class, we can restrict the creation of the objects. 
Similar to Java, Scala allows us to make the primary constructor as private so that we can use method definition to perform controlled creation of objects. 

Companion Object (Ingredient #2)

 Companion object is analogous to utility class in Java. A utility class in Java will contain only static methods, thus makes easy to invoke methods without object. In Scala, a companion object will have the same name of the class in the same file and all the methods that are declared will be static. 

The following code sample explains the implementation of Singleton in Scala using above mentioned 2 ingredients.
/**
 * Singleton object using companion object in Scala
 *  
 * */
class Building private {
 
 // Overriding toString method
 override def toString = "This is a building object"
}

/**
 * Companion object for Building
 */
object Building {
 
 val building = new Building
 
 // Defining getInstance method returning building object
 def getInstance = building
}
 
/**
 * Testing the singleton object
 * 
 * */
 object BuildingTest extends App{
  
  val oneStorey = Building.getInstance
  
  println(oneStorey)
 }
The result will be printed as This is a building object

Comments

Popular posts from this blog

Trait, an interface in Scala

Quickstart with Angular 2/4