Scala (1): Singleton Pattern by Scala

Singleton object means there is only one object in a instance, which is always used in factory pattern. Meanwhile, Singleton object can have the same name with its class; in this case, this singleton object is called companion object. Normally, we use companion object as factory method.

In Scala, it designs object to be part of Scala’s module system.

In Scala, Singleton is very simply which is just object.

object Singleton {
   def say() = println("hello scala")
 }

Here is the test code:

object Test extends APP {
   Singleton.say() // output: hello scala
 }

If you want to learn why it is so simply in Scala, let’s continue.

Scala compiler will compile Singleton.scala to two files, one is Singleton.java and the other is Singleton$.java. The following is the code:

/// Singleton.java
 public final class Singleton
 {
   public static void say()
   {
     Singleton$.MODULE$.say();
   }
 }
 /// Singleton$.java
 public final class Singleton$
 {
   public static final MODULE$;
   static
   {
     new ();
   }
   public void say()
   {
     Predef$.MODULE$.print("hello scala");
   }
   private Singleton$()
   {
     MODULE$ = this;
   }
 }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s