Singleton Pattern

Definition

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

Explanation

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

There is criticism of the use of the singleton pattern, as some consider it an anti-pattern, judging that it is overused, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application.

Common use:

  • The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.
  • Facade objects are often singletons because only one Facade object is required.
  • State objects are often singletons.
  • Singletons are often preferred to global variables because: They do not pollute the global namespace (or, in languages with namespaces, their containing namespace) with unnecessary variables.
  • They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.

Implementation of a singleton pattern must satisfy the single instance and global access principles. It requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects. The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made private. Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed.

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation. The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated.

Screencast

TypeScript Code

module Singleton {
    class Singleton {
        public counter: number = 0;
        private static _instance: Singleton = null;

        constructor() {
            if (Singleton._instance) {
                throw new Error("Error: Instantiation failed: Use Singleton.current instead of new.");
            }

            Singleton._instance = this;
        }

        public static get current(): Singleton {
            if (Singleton._instance === null) {
                Singleton._instance = new Singleton();
            }

            return Singleton._instance;
        }

        public display() {
            Output.WriteLine("The Singleton counter has a value of:" + this.counter);
        }
    }

    window.addEventListener("load", function () {
        var singleton1 = Singleton.current;
        singleton1.display();

        var singleton2 = Singleton.current;
        singleton2.counter++;
        singleton1.display();

        try {
            var singleton3 = new Singleton();
        } catch (error) {
            Output.WriteLine(error.message);
        }

        singleton2.counter++;
        singleton1.display();
    });
}

Output