Friday, January 26, 2018

Singleton design pattern

Greetings!

Singleton design pattern is one of the most commonly used pattern. It falls under creational patterns.

"Ensure a class only has one instance and provide a global point of access to it."

There are multiple ways to create a singleton class.
  • Eagerly initialization - instance of class is always created, whether we use it or not. (anyway we are creating a class to use it aren't we?)
  • Lazily initialization - create the instance at first call. we have to deal with threading issues.
  • Use of a holder - Bill Pugh method. use an inner class to create the instance hence create the instance lazily and can avoid threading issues.
There are ways to break singleton behavior by force and few tricks to prevent them.
  • Cloning - implement clone() and throw an exception to prevent this
  • Reflection - throws an exception in constructor to solve this
  • Different class loaders - implement getClass()

No comments:

Post a Comment