Thursday, 30 November 2017

Singleton Design Pattern


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 a file system or only a 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 is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

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

Where to use
Singleton pattern should be used when we must ensure that only one instance of a class is created and when the instance must be available through all the code. A special care should be taken in multi-threading environments when multiple threads must access the same resources through the same singleton object.

Common Usage
There are many common situations when singleton pattern is used:
- Logger Classes
- Configuration Classes
- Accessing resources in shared mode
- Other design patterns implemented as Singletons: Factories and Abstract Factories, Builder, Prototype

Example: Lazy Singleton in Java, Early Singleton in Java

Applicability
Use the Singleton pattern when 1. there must be exactly one instance of a class, and it must be accessible to clients from a wellknown access point. 2. when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

Benefit(s)
1. Controlled access to sole instance.
2. Reduced name space.
3. Permits refinement of operations and representation.
4. Permits a variable number of instances.
5. More flexible than class operations.

Happy Learning.

1 comment: