Wednesday, August 24, 2011

Scala - The singleton pattern

As a first example of how to use Scala, I want to show to you how you could implement the singleton pattern.
This is a basic pattern used when you want to ensure that no more than one instance of a class can be living in your application at the same time. A method, usually called "instance", is used to retrieve this single instance. Also, the lazy pattern is recommended: do not create the singleton until it's needed.

First, how a Java singleton looks like? Well...
public class Singleton {
    private static final class SingletonHolder{
        private static final Singleton INSTANCE = new Singleton();
    }
   
    private Singleton() {}
   
    public static final Singleton instance(){
        return SingletonHolder.INSTANCE;
    }
}

Instead, with Scala it would look like.
class Singleton private () {

}

object Singleton {
  private lazy val INSTANCE =  new Singleton()
  
  def instance = INSTANCE
}

That's all

No comments:

Post a Comment