SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternMudasir Qazi
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Sameer Rathoud
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternMudasir Qazi
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns pptmkruthika
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan GoleChetan Gole
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonJonathan Simon
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns pptAman Jain
 
Visitor Pattern
Visitor PatternVisitor Pattern
Visitor PatternIder Zheng
 

Mais procurados (20)

Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
Prototype_pattern
Prototype_patternPrototype_pattern
Prototype_pattern
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Design patterns tutorials
Design patterns tutorialsDesign patterns tutorials
Design patterns tutorials
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 
Visitor Pattern
Visitor PatternVisitor Pattern
Visitor Pattern
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

(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
 
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
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
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
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...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
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
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
 
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
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
(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
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
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
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 

Último (20)

(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...
 
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...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
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
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
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
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
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...
 
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
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
(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...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
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...
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 

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