SlideShare a Scribd company logo
4
Most read
6
Most read
16
Most read
Singleton Design Pattern
From definition to implementation
Mudasir Qazi - mudasirqazi00@gmail.com 116-Dec-14
Contents / Agenda
• Definition and types
• Advantages and usage
• UML – Class diagram
• UML – Sequence diagram
• Singleton in Memory (Memory allocation)
• Implementation – Lazy Singleton (C# and Java)
• Implementation – Early Singleton (C#)
• Thread-Safe Singleton in C#
• Thread-Safe Singleton in Java
• Double-check locking singleton (thread-safe)
• Static Block Implementation (thread-safe)
• Implementation – N-Singleton (C# and Java)
Mudasir Qazi - mudasirqazi00@gmail.com 216-Dec-14
Definition
• Ensures that a class has only one instance, and provide a global point
to access this instance.
• In other words, a class must ensure that only single instance should be
created and single object can be used by all other classes.
• There are two forms of singleton design pattern
1. Early Instantiation: Creation of instance at load time.
2. Lazy Instantiation: Creation of instance when required.
3. N-Singleton: Create specific number of objects.
• It comes under “Creational Design Patterns” category.
Mudasir Qazi - mudasirqazi00@gmail.com 316-Dec-14
Advantages and Usage
• Advantages
• Saves memory because object is not created at each request. Only single
instance is reused again and again.
• In cases when object creation is very costly (time taking), we don’t have to
create new object each time we need it. We just access already created object.
• Usage
• Singleton pattern is mostly used in multi-threaded and database applications.
• It is used in logging, caching, thread pools, configuration settings etc.
• For database connection, because one connection is enough for most
applications and too much connections can make application slow.
Mudasir Qazi - mudasirqazi00@gmail.com 416-Dec-14
Usage Example
Mudasir Qazi - mudasirqazi00@gmail.com 516-Dec-14
UML - Class Diagram
Mudasir Qazi - mudasirqazi00@gmail.com 6
We need
1) Private Static Instance of Class
2) Private Constructor
3) Public Static method with return type of
Class to access that instance.
16-Dec-14
UML - Sequence Diagram
Mudasir Qazi - mudasirqazi00@gmail.com 716-Dec-14
Singleton in Heap
Mudasir Qazi - mudasirqazi00@gmail.com 8
Only one object is created, all
other threads call the same
object without creating new
one.
16-Dec-14
Lazy Instantiation (C# and Java)
Mudasir Qazi - mudasirqazi00@gmail.com 9
This is very common implementation
of Singleton but is not very good in
Multithreaded applications.
Because there is a possibility that
multiple thread can call the method
getInstance on same time due to
Race Condition. If happens so, then it
would create multiple instances.
Means meaning of singleton can will
not be achieved.
16-Dec-14
Lazy Instantiation (C# and Java) - Test
Mudasir Qazi - mudasirqazi00@gmail.com 1016-Dec-14
Early / Eager Instantiation (C#)
Mudasir Qazi - mudasirqazi00@gmail.com 11
This is possible in C# because of
‘readonly’ keyword. Java don’t
have ‘readonly’ keyword (but it
can be achieved using final
keyword, see next slide). And
also note that ‘getInstance’ is a
property (getter/setter) for
variable instance, it has no
parenthesis after its name.
Note that, is this not thread
safe. If you are working in multi
threaded system then you
should not use this
implementation.
16-Dec-14
Thread-Safe Singleton in C#
Mudasir Qazi - mudasirqazi00@gmail.com 12
Implementation in this picture will be thread
safe. In any condition there would be one and
only one instance of the Singleton class in
Multithreaded system.
16-Dec-14
Thread-Safe Singleton in Java
Mudasir Qazi - mudasirqazi00@gmail.com 13
Advantages:
1) The instance is not constructed until the class is used.
2) There is no need to synchronize the getInstance() method meaning all threads will see the same instance
and no (expensive) locking is required.
3) The final keyword means that the instance can not be redefined, ensuring that one (and only one) instance
will ever exists.
4) This is thread safe. (This is best implementation for both Multithreaded and single threaded applications)
16-Dec-14
Double Check Locking Implementation (Lazy)
Mudasir Qazi - mudasirqazi00@gmail.com 14
These implementations also comes under
synchronized or thread safe implementations.
Left one is better.
16-Dec-14
Static Block Initialization
Mudasir Qazi - mudasirqazi00@gmail.com 15
This is not very common use of singleton. But it also exists so I mentioned it.
16-Dec-14
N-Singleton Implementation (N=3)
Mudasir Qazi - mudasirqazi00@gmail.com 16
MAX = 3,
Means that maximum 3
instances can created.
16-Dec-14
N-Singleton Implementation (N=3) - Output
Mudasir Qazi - mudasirqazi00@gmail.com 17
Output shows that all 3
instances are different.
If you do same test with
Singleton (or give MAX = 0
in N-Singleton) the output
would be
“obj1=obj2=obj3”
16-Dec-14
N-Singleton as Singleton (N=0)
Mudasir Qazi - mudasirqazi00@gmail.com 18
Here N=0 (we give count < MAX
condition so N=0 actually means
that 1 instance will be created. If
we have given <= condition then
we have given N=1) to create
single instance.
16-Dec-14
N-Singleton as Singleton (N=0) - Output
Mudasir Qazi - mudasirqazi00@gmail.com 19
Output proves that only
one instance is created.
16-Dec-14

More Related Content

PPTX
The Singleton Pattern Presentation
PPTX
Using Azure DevOps to continuously build, test, and deploy containerized appl...
PDF
Polymorphism in oop
PPTX
work life balance ppt
PPTX
Design pattern-presentation
PPTX
Mathematical Induction
PPSX
Team Building Presentation
PDF
Logical equivalence, laws of logic
The Singleton Pattern Presentation
Using Azure DevOps to continuously build, test, and deploy containerized appl...
Polymorphism in oop
work life balance ppt
Design pattern-presentation
Mathematical Induction
Team Building Presentation
Logical equivalence, laws of logic

What's hot (20)

PPT
Singleton design pattern
PPTX
Gof design patterns
PPTX
Factory Method Pattern
PPTX
Singleton Design Pattern - Creation Pattern
PPT
Design patterns ppt
PPTX
Design Pattern - Factory Method Pattern
PPTX
Singleton Pattern (Sole Object with Global Access)
PDF
Introduction to Design Pattern
PPT
Introduction to Design Patterns and Singleton
PPT
Flyweight pattern
PPTX
Design Patterns - Abstract Factory Pattern
PPTX
Design pattern (Abstract Factory & Singleton)
PPTX
Let us understand design pattern
PPTX
Proxy Design Pattern
PPTX
[OOP - Lec 08] Encapsulation (Information Hiding)
PPSX
PPT
Design Patterns
PPTX
JAVA AWT
PDF
Gof design pattern
PPTX
Android share preferences
Singleton design pattern
Gof design patterns
Factory Method Pattern
Singleton Design Pattern - Creation Pattern
Design patterns ppt
Design Pattern - Factory Method Pattern
Singleton Pattern (Sole Object with Global Access)
Introduction to Design Pattern
Introduction to Design Patterns and Singleton
Flyweight pattern
Design Patterns - Abstract Factory Pattern
Design pattern (Abstract Factory & Singleton)
Let us understand design pattern
Proxy Design Pattern
[OOP - Lec 08] Encapsulation (Information Hiding)
Design Patterns
JAVA AWT
Gof design pattern
Android share preferences
Ad

Similar to Design Pattern - Singleton Pattern (20)

PDF
Concurrency in Java
PDF
Concurrent Programming in Java
PDF
Java Threads
PDF
Tests immutable when refactoring - SegFault Unconference Cracow 2019
DOCX
25 java tough interview questions
PPT
10-design-patterns1.ppt.software engineering
DOC
Programming paradigms
PPTX
Concurrency
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
PPTX
Exploring Kotlin language basics for Android App development
PPT
12 multi-threading
 
PPT
Java Threads and Concurrency
PDF
Design patterns - Common Solutions to Common Problems - Brad Wood
PPTX
Thread&amp;multithread
PPT
Java Multithreading and Concurrency
PDF
Design patterns in javascript
PDF
The Concept Of Multithreading In Java Programming
PDF
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
PDF
Cloudsim_openstack_aws_lastunit_bsccs_cloud computing
PPTX
Slide 7 Thread-1.pptx
Concurrency in Java
Concurrent Programming in Java
Java Threads
Tests immutable when refactoring - SegFault Unconference Cracow 2019
25 java tough interview questions
10-design-patterns1.ppt.software engineering
Programming paradigms
Concurrency
Advanced Introduction to Java Multi-Threading - Full (chok)
Exploring Kotlin language basics for Android App development
12 multi-threading
 
Java Threads and Concurrency
Design patterns - Common Solutions to Common Problems - Brad Wood
Thread&amp;multithread
Java Multithreading and Concurrency
Design patterns in javascript
The Concept Of Multithreading In Java Programming
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Cloudsim_openstack_aws_lastunit_bsccs_cloud computing
Slide 7 Thread-1.pptx
Ad

More from Mudasir Qazi (12)

PPTX
Database - SQL Joins
PPTX
Database - Normalization
PPTX
Database - Entity Relationship Diagram (ERD)
PPTX
OOP - Understanding association, aggregation, composition and dependency
PPTX
OOP - Polymorphism
PPTX
OOP - Java is pass-by-value
PPTX
OOP - Benefits and advantages of OOP
PPTX
Design Pattern - Observer Pattern
PPTX
Design Pattern - MVC, MVP and MVVM
PPTX
Design Pattern - Introduction
PPTX
Design pattern - Facade Pattern
PPTX
Design Pattern - Chain of Responsibility
Database - SQL Joins
Database - Normalization
Database - Entity Relationship Diagram (ERD)
OOP - Understanding association, aggregation, composition and dependency
OOP - Polymorphism
OOP - Java is pass-by-value
OOP - Benefits and advantages of OOP
Design Pattern - Observer Pattern
Design Pattern - MVC, MVP and MVVM
Design Pattern - Introduction
Design pattern - Facade Pattern
Design Pattern - Chain of Responsibility

Recently uploaded (20)

PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
PPT on Performance Review to get promotions
PPTX
Geodesy 1.pptx...............................................
PPTX
CH1 Production IntroductoryConcepts.pptx
DOCX
573137875-Attendance-Management-System-original
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
UNIT 4 Total Quality Management .pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Digital Logic Computer Design lecture notes
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
R24 SURVEYING LAB MANUAL for civil enggi
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
OOP with Java - Java Introduction (Basics)
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPT on Performance Review to get promotions
Geodesy 1.pptx...............................................
CH1 Production IntroductoryConcepts.pptx
573137875-Attendance-Management-System-original
Lecture Notes Electrical Wiring System Components
UNIT 4 Total Quality Management .pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
CYBER-CRIMES AND SECURITY A guide to understanding
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Digital Logic Computer Design lecture notes

Design Pattern - Singleton Pattern

  • 1. Singleton Design Pattern From definition to implementation Mudasir Qazi - mudasirqazi00@gmail.com 116-Dec-14
  • 2. Contents / Agenda • Definition and types • Advantages and usage • UML – Class diagram • UML – Sequence diagram • Singleton in Memory (Memory allocation) • Implementation – Lazy Singleton (C# and Java) • Implementation – Early Singleton (C#) • Thread-Safe Singleton in C# • Thread-Safe Singleton in Java • Double-check locking singleton (thread-safe) • Static Block Implementation (thread-safe) • Implementation – N-Singleton (C# and Java) Mudasir Qazi - mudasirqazi00@gmail.com 216-Dec-14
  • 3. Definition • Ensures that a class has only one instance, and provide a global point to access this instance. • In other words, a class must ensure that only single instance should be created and single object can be used by all other classes. • There are two forms of singleton design pattern 1. Early Instantiation: Creation of instance at load time. 2. Lazy Instantiation: Creation of instance when required. 3. N-Singleton: Create specific number of objects. • It comes under “Creational Design Patterns” category. Mudasir Qazi - mudasirqazi00@gmail.com 316-Dec-14
  • 4. Advantages and Usage • Advantages • Saves memory because object is not created at each request. Only single instance is reused again and again. • In cases when object creation is very costly (time taking), we don’t have to create new object each time we need it. We just access already created object. • Usage • Singleton pattern is mostly used in multi-threaded and database applications. • It is used in logging, caching, thread pools, configuration settings etc. • For database connection, because one connection is enough for most applications and too much connections can make application slow. Mudasir Qazi - mudasirqazi00@gmail.com 416-Dec-14
  • 5. Usage Example Mudasir Qazi - mudasirqazi00@gmail.com 516-Dec-14
  • 6. UML - Class Diagram Mudasir Qazi - mudasirqazi00@gmail.com 6 We need 1) Private Static Instance of Class 2) Private Constructor 3) Public Static method with return type of Class to access that instance. 16-Dec-14
  • 7. UML - Sequence Diagram Mudasir Qazi - mudasirqazi00@gmail.com 716-Dec-14
  • 8. Singleton in Heap Mudasir Qazi - mudasirqazi00@gmail.com 8 Only one object is created, all other threads call the same object without creating new one. 16-Dec-14
  • 9. Lazy Instantiation (C# and Java) Mudasir Qazi - mudasirqazi00@gmail.com 9 This is very common implementation of Singleton but is not very good in Multithreaded applications. Because there is a possibility that multiple thread can call the method getInstance on same time due to Race Condition. If happens so, then it would create multiple instances. Means meaning of singleton can will not be achieved. 16-Dec-14
  • 10. Lazy Instantiation (C# and Java) - Test Mudasir Qazi - mudasirqazi00@gmail.com 1016-Dec-14
  • 11. Early / Eager Instantiation (C#) Mudasir Qazi - mudasirqazi00@gmail.com 11 This is possible in C# because of ‘readonly’ keyword. Java don’t have ‘readonly’ keyword (but it can be achieved using final keyword, see next slide). And also note that ‘getInstance’ is a property (getter/setter) for variable instance, it has no parenthesis after its name. Note that, is this not thread safe. If you are working in multi threaded system then you should not use this implementation. 16-Dec-14
  • 12. Thread-Safe Singleton in C# Mudasir Qazi - mudasirqazi00@gmail.com 12 Implementation in this picture will be thread safe. In any condition there would be one and only one instance of the Singleton class in Multithreaded system. 16-Dec-14
  • 13. Thread-Safe Singleton in Java Mudasir Qazi - mudasirqazi00@gmail.com 13 Advantages: 1) The instance is not constructed until the class is used. 2) There is no need to synchronize the getInstance() method meaning all threads will see the same instance and no (expensive) locking is required. 3) The final keyword means that the instance can not be redefined, ensuring that one (and only one) instance will ever exists. 4) This is thread safe. (This is best implementation for both Multithreaded and single threaded applications) 16-Dec-14
  • 14. Double Check Locking Implementation (Lazy) Mudasir Qazi - mudasirqazi00@gmail.com 14 These implementations also comes under synchronized or thread safe implementations. Left one is better. 16-Dec-14
  • 15. Static Block Initialization Mudasir Qazi - mudasirqazi00@gmail.com 15 This is not very common use of singleton. But it also exists so I mentioned it. 16-Dec-14
  • 16. N-Singleton Implementation (N=3) Mudasir Qazi - mudasirqazi00@gmail.com 16 MAX = 3, Means that maximum 3 instances can created. 16-Dec-14
  • 17. N-Singleton Implementation (N=3) - Output Mudasir Qazi - mudasirqazi00@gmail.com 17 Output shows that all 3 instances are different. If you do same test with Singleton (or give MAX = 0 in N-Singleton) the output would be “obj1=obj2=obj3” 16-Dec-14
  • 18. N-Singleton as Singleton (N=0) Mudasir Qazi - mudasirqazi00@gmail.com 18 Here N=0 (we give count < MAX condition so N=0 actually means that 1 instance will be created. If we have given <= condition then we have given N=1) to create single instance. 16-Dec-14
  • 19. N-Singleton as Singleton (N=0) - Output Mudasir Qazi - mudasirqazi00@gmail.com 19 Output proves that only one instance is created. 16-Dec-14