0% found this document useful (0 votes)
9 views10 pages

Singleton

Uploaded by

wubetayalew2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

Singleton

Uploaded by

wubetayalew2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 10

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 

You might also like