AlgoViz

Singleton

medium 60 min

One object and one way to reach it.

Watch lesson4:52

Where it shows up

The same pattern appears across everyday software.

  • java.lang.Runtime

    The documentation says that every Java application has a single instance of class `Runtime`, obtained from `getRuntime`. An application can not create its own.

  • Python logging

    Several calls to `logging.getLogger(name)` with the same name return a reference to the same logger: one per name, a multiton.

  • Python modules

    The Python FAQ recommends a config module to share values across a program, and calls a module the basis for implementing the singleton pattern. `None` is a singleton too.

  • Node.js modules

    Modules are cached after the first load: every `require('foo')` that resolves to the same file gets the same object.

  • Kotlin object

    An `object` declaration is a singleton in the language. It is initialized on first access, and the initialization is thread safe.

  • Scala object

    An object is a class with exactly one instance, created lazily when it is referenced.

  • Go sync.Once

    A value that performs exactly one action, also with many goroutines. Usual for a lazily opened resource.

  • Rust OnceLock

    A cell that can be written once and may be used in statics. `LazyLock` is built for lazy values.

  • .NET Lazy<T>

    Lazy creation with a thread safe default. The framework owns the checked lock, not you.

  • Spring beans

    The default scope is singleton: one per container and bean definition. Spring's documentation explains how this differs from the Singleton of the book.

  • Angular services

    A service provided globally is one shared instance for the application, handed over by injection.