Skip to content

Singleton

Roberto Fronteddu edited this page Feb 1, 2023 · 3 revisions

The Singleton is a Creational Design Pattern. Create a class that can be instantiated only once accessible globally through a single point.

Usefull when

  • We want to ensure that only a single instance of a class exists

Implementation Steps

  1. Control Instance creation
    • Constructors must not be accessible globally
    • Subclassing/inheritance must not be allowed
  2. Keep Track of the single instance
  3. Give access to the instance with a public method

Example

singleton-uml

  • A singleton class has a private INSTANCE and provides a static method to retrieve the INSTANCE.

Considerations

  • Any state added to a singleton becomes part of the global state of the application. Note that having a big global state is symptomatic of a bad design.
  • Two options for implementing a singleton: Early initialization (Eager Singleton): Creates a singleton as soon as a class is loaded. Lazy Singleton: The instance is not created until requested.
  • Use the Eager approach unless a lazy approach is needed.
  • If you need to use constructor arguments, you may want to use a simple factory or factory method pattern instead.

Pitfalls

  • Make sure that singletons are not carrying a lot of mutable global states (considered anti-pattern).
  • Can be deceiving in terms of true dependencies since they are globally accessible.
  • Hard to unit test and mock.
  • Static variables are held per class loader and not per JVM. Static variables may not be truly singletons in a web application or container (tomcat). This is a problem if the instance is tied to an external resource.

Comparison with factory method:

Singleton

  • primary intent is to ensure that only one instance of a class is ever created.
  • Singleton should not use arguments.

Factory method

  • is primarily used to isolate client code from object creation and delegate object creation to subclasses.
  • The factory method allows parametrized initialization.

Real-Life Example:

  • java.lang.Runtime
Clone this wiki locally