Singleton Pattern   «Prev 

Singleton: Structure Diagrams

This course uses rectangles for classes and rounded rectangles for objects.
Connections between pointers and the objects they point to are indicated by arrows. As much information about a class's methods and fields as is important is provided.

Singleton Design Pattern

In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object.
This is useful when exactly one object is needed to coordinate actions across the system.
Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist. It is also considered an anti-pattern since it is often used as a euphemism for global variable. In C++ it also serves to isolate from the unpredictability of the order of dynamic initialization, returning control to the programmer.

Singleton Implementation

Implementation of a Singleton Pattern must satisfy the single instance and global access principles. The Singleton 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
  1. a simple static instance of a class and
  2. a singleton:
although a singleton can be implemented as a static instance, it can also be constructed, requiring no memory or resources until needed.
Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, it really has to be a singleton.
The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time and 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.