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).
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.
More patterns are on the way and they will be soon on my github soon.
No comments:
Post a Comment