Loading...

Java Singleton Design Pattern with Examples

Faisal / Design Patterns,Java

Singleton Pattern

As one of the Gangs of Four Design Patterns Singleton falls under the Creational Design Pattern category.  Only a single instance of the class exists in a single instance of the java virtual machine, hence it must provide a global accessing object which can be used by others to get the class data.

It is implemented in many different ways.  It is used for example in logging, caching, thread pool and driver objects. Also in core classes like java.lang.Runtime and java.awt.Desktop.

The following common concepts are found in different approaches of implementing Singleton Pattern.

  • A single private constructor that prevents it’s instantiation more than once.
  • A private static variable of the class that is the only available single instance of the calss.
  • Public static method that returns a instance of the class, accessible by other outer methods.

Leave a Comment