Design Pattern: Singleton Pattern
Design Pattern: Singleton Pattern
Intent
Ensuring a class only has one instance Providing a global point of access to it.
Motivation
Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system and one window manager. A digital filter will have one A/D converter. An accounting system will be dedicated to serving one company.
How do we ensure that a class has only one instance and that the instance is easily accessible?
A global variable makes an object accessible, but it doesn't stops instantiation of multiple objects.
A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance. This is the Singleton pattern.
Applicability
There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.
Structure
Singleton
Participants
Singleton
defines
an Instance operation that lets clients access its unique instance. Instance is a class operation (that is, a static method in JAVA and a static member function in C++). may be responsible for creating its own unique instance.
Collaborations
Consequences
Controlled access to sole instance Reduced name space Permits refinement of operations and representation Permits a variable number of instances More flexible than class operations
Implementation
public class { private static Singeton uniqueInstance; Private Singleton () { //required codes } public static synchronized Singleton getInstance() { if(uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } //other methods }