Singleton Pattern   «Prev  Next»
Lesson 14

Singleton Design Pattern Conclusion

In this module, you learned about the Singleton design pattern.
The Singleton pattern is a creational pattern that lets you create a single instance of the class and provides and controls access to it through a public static method. A nonpublic constructor prevents clients from creating new instances of the class.
The Singleton pattern is used to ensure that only one object of a particular class is instantiated. The Singleton pattern is used for single-threaded applications.

Review the primary elements that make up the Singleton:

Motivation

Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager or only one print spooler. Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
The singleton pattern involves only one class which is required to instantiate itself and to make sure it creates not more than one instance.
At the same time it provides a global point of access to that instance. In this case the same instance can be accessed from anywhere, making it impossible to directly invoke the constructor each time.

Intent

  1. Ensure that only one instance of a class is created.
  2. Provide a global point of access to the object.



Implementation

The implementation involves
  1. a static member in the "Singleton" class,
  2. a private constructor and
  3. a static public method that returns a reference to the static member.

UML Class Diagram for the Singleton Pattern

The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients.
getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.

Next Module

The upcoming modules introduce you to many more patterns.
In the next module, you will have a chance to work with another creational pattern, the "factory method" pattern.