Singleton Design Pattern
Singleton Pattern
The Singleton pattern ensures that a class has
only one instance/object and provides a global
point of access to it.
Examples:
– Student ID generation class.
– There should be only one instance of a WindowManager.
– There should be only one instance of a filesystem.
Singleton Pattern
Ensures a class has only one instance,
and provides a global point of access
to it.
Use the Singleton pattern when there must be
exactly one instance of a class, and it must be
accessible to clients from a well-known access
point.
Singleton pattern is implemented by using a
private constructor and a static method combined
with a static variable.
Singleton Pattern (cont.)
Singleton with lazy instantiation
class Singleton {
private static Singleton instance=null;
private Singleton(){
}
static Singleton getInstance() {
if (instance == null)
{
instance = new Singleton();
}
else
return instance;
}
}
Singleton Pattern (cont.)
Move to an eagerly created
instance rather than a lazily created
one
Singleton Pattern
(cont.)
Use “double-checked locking” to reduce
the use of synchronization in getInstance()
Singleton Pattern
(cont.)
In multi-threading add synchronized
to getInstance()
In Summary
The singleton pattern ensures that there is just
one instance of a class.
The singleton pattern provides a global access
point.
The pattern is implemented by using a private
constructor and a static method combined with
a static variable.
Possible problems with multithreading.
QUESTIONS PLEASE