SlideShare a Scribd company logo
1 of 19
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

What's hot

Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternMudasir Qazi
 
Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patternsThaichor Seng
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan GoleChetan Gole
 
Object Oriented Testing
Object Oriented TestingObject Oriented Testing
Object Oriented TestingAMITJain879
 
Gof design pattern
Gof design patternGof design pattern
Gof design patternnaveen kumar
 
Presentation on Template Method Design Pattern
Presentation on Template Method Design PatternPresentation on Template Method Design Pattern
Presentation on Template Method Design PatternAsif Tayef
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 

What's hot (20)

Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
Prototype_pattern
Prototype_patternPrototype_pattern
Prototype_pattern
 
Prototype Design Pattern
Prototype Design PatternPrototype Design Pattern
Prototype Design Pattern
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Proxy Design Pattern
Proxy Design PatternProxy Design Pattern
Proxy Design Pattern
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
 
Object Oriented Testing
Object Oriented TestingObject Oriented Testing
Object Oriented Testing
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
Presentation on Template Method Design Pattern
Presentation on Template Method Design PatternPresentation on Template Method Design Pattern
Presentation on Template Method Design Pattern
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 

Similar to Design Pattern - Singleton Pattern

Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaLakshmi Narasimhan
 
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Grzegorz Miejski
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questionsArun Banotra
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Design patterns - Common Solutions to Common Problems - Brad Wood
Design patterns -  Common Solutions to Common Problems - Brad WoodDesign patterns -  Common Solutions to Common Problems - Brad Wood
Design patterns - Common Solutions to Common Problems - Brad WoodOrtus Solutions, Corp
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK toolsHaribabu Nandyal Padmanaban
 
Cloudsim_openstack_aws_lastunit_bsccs_cloud computing
Cloudsim_openstack_aws_lastunit_bsccs_cloud computingCloudsim_openstack_aws_lastunit_bsccs_cloud computing
Cloudsim_openstack_aws_lastunit_bsccs_cloud computingMrSameerSTathare
 
Insecure Java Deserialization
Insecure Java DeserializationInsecure Java Deserialization
Insecure Java DeserializationShiv Sahni
 

Similar to Design Pattern - Singleton Pattern (20)

Concurrency in Java
Concurrency in JavaConcurrency in Java
Concurrency in Java
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questions
 
Programming paradigms
Programming paradigmsProgramming paradigms
Programming paradigms
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Design patterns - Common Solutions to Common Problems - Brad Wood
Design patterns -  Common Solutions to Common Problems - Brad WoodDesign patterns -  Common Solutions to Common Problems - Brad Wood
Design patterns - Common Solutions to Common Problems - Brad Wood
 
Thread&amp;multithread
Thread&amp;multithreadThread&amp;multithread
Thread&amp;multithread
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
 
Cloudsim_openstack_aws_lastunit_bsccs_cloud computing
Cloudsim_openstack_aws_lastunit_bsccs_cloud computingCloudsim_openstack_aws_lastunit_bsccs_cloud computing
Cloudsim_openstack_aws_lastunit_bsccs_cloud computing
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
Insecure Java Deserialization
Insecure Java DeserializationInsecure Java Deserialization
Insecure Java Deserialization
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
 

More from Mudasir Qazi

Database - SQL Joins
Database - SQL JoinsDatabase - SQL Joins
Database - SQL JoinsMudasir Qazi
 
Database - Normalization
Database - NormalizationDatabase - Normalization
Database - NormalizationMudasir Qazi
 
Database - Entity Relationship Diagram (ERD)
Database - Entity Relationship Diagram (ERD)Database - Entity Relationship Diagram (ERD)
Database - Entity Relationship Diagram (ERD)Mudasir Qazi
 
OOP - Understanding association, aggregation, composition and dependency
OOP - Understanding association, aggregation, composition and dependencyOOP - Understanding association, aggregation, composition and dependency
OOP - Understanding association, aggregation, composition and dependencyMudasir Qazi
 
OOP - Polymorphism
OOP - PolymorphismOOP - Polymorphism
OOP - PolymorphismMudasir Qazi
 
OOP - Java is pass-by-value
OOP - Java is pass-by-valueOOP - Java is pass-by-value
OOP - Java is pass-by-valueMudasir Qazi
 
OOP - Benefits and advantages of OOP
OOP - Benefits and advantages of OOPOOP - Benefits and advantages of OOP
OOP - Benefits and advantages of OOPMudasir Qazi
 
Design Pattern - Observer Pattern
Design Pattern - Observer PatternDesign Pattern - Observer Pattern
Design Pattern - Observer PatternMudasir Qazi
 
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMMudasir Qazi
 
Design Pattern - Introduction
Design Pattern - IntroductionDesign Pattern - Introduction
Design Pattern - IntroductionMudasir Qazi
 
Design pattern - Facade Pattern
Design pattern - Facade PatternDesign pattern - Facade Pattern
Design pattern - Facade PatternMudasir Qazi
 
Design Pattern - Chain of Responsibility
Design Pattern - Chain of ResponsibilityDesign Pattern - Chain of Responsibility
Design Pattern - Chain of ResponsibilityMudasir Qazi
 

More from Mudasir Qazi (12)

Database - SQL Joins
Database - SQL JoinsDatabase - SQL Joins
Database - SQL Joins
 
Database - Normalization
Database - NormalizationDatabase - Normalization
Database - Normalization
 
Database - Entity Relationship Diagram (ERD)
Database - Entity Relationship Diagram (ERD)Database - Entity Relationship Diagram (ERD)
Database - Entity Relationship Diagram (ERD)
 
OOP - Understanding association, aggregation, composition and dependency
OOP - Understanding association, aggregation, composition and dependencyOOP - Understanding association, aggregation, composition and dependency
OOP - Understanding association, aggregation, composition and dependency
 
OOP - Polymorphism
OOP - PolymorphismOOP - Polymorphism
OOP - Polymorphism
 
OOP - Java is pass-by-value
OOP - Java is pass-by-valueOOP - Java is pass-by-value
OOP - Java is pass-by-value
 
OOP - Benefits and advantages of OOP
OOP - Benefits and advantages of OOPOOP - Benefits and advantages of OOP
OOP - Benefits and advantages of OOP
 
Design Pattern - Observer Pattern
Design Pattern - Observer PatternDesign Pattern - Observer Pattern
Design Pattern - Observer Pattern
 
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVM
 
Design Pattern - Introduction
Design Pattern - IntroductionDesign Pattern - Introduction
Design Pattern - Introduction
 
Design pattern - Facade Pattern
Design pattern - Facade PatternDesign pattern - Facade Pattern
Design pattern - Facade Pattern
 
Design Pattern - Chain of Responsibility
Design Pattern - Chain of ResponsibilityDesign Pattern - Chain of Responsibility
Design Pattern - Chain of Responsibility
 

Recently uploaded

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 

Recently uploaded (20)

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 

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