SlideShare une entreprise Scribd logo
1  sur  14
Software Construction Design Pattern Presentation
 Definition and types
 Creational Patterns
 Advantages and usage
 Discuss Problem
 Class diagram
 Implementation
 Lazy Instantiation
 Easy Instantiation
 Dealing with multithreading
Singleton Design Pattern comes under “Creational Design Patterns” category.
Creational design patterns are design patterns that deal with object
creation mechanisms, trying to create objects in a manner suitable to
the situation. The basic form of object creation could result in design
problems or added complexity to the design. Creational design
patterns solve this problem by somehow controlling this object
creation.
“ ”
 In software engineering, the singleton pattern is a software design pattern that
provides the possibility to control the number of instances (mostly one) that are
allowed to be made. We also receive a global point of access to it (them)
 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.
 Imagine an intersection where several roads meet, and where the cars need to
ensure they do not crash into each other when crossing this intersection.
 Assuming there were no traffic lights to guide them, we would need a police officer
standing in the middle to direct traffic. This officer would be a real life
approximation of a singleton.
 The officer would receive visual queues from all roads, telling him which one is
filling up the most with cars. With all this information, he would be able to decide
which road to let the cars come through, and which roads to block.
 This would be significantly more complex if there were several officers controlling
the intersection, where they would all be receiving visual queues from the roads,
would have to communicate with each other and then collectively decide which
road to let traffic come from.
 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.
 When only one instance or a specific number of instances of a class are allowed.
 It is used in logging, caching, web server, etc.
 For database connection, because one connection is enough for most applications and
too much connections can make application slow.
 If your program needs to do logging, you may want all output to be written to one
log file. That could lead to resource conflicts and errors.
objectA objectB objectC
loggerA loggerB loggerC
LogFile.txt
 With a singleton logger object, you don’t need to worry about several different
objects trying to write to the same file, at the same time.
objectA objectB objectC
loggerSingleton
LogFile.txt
Singleton
- static uniqueInstance
// Other useful Singleton data...
- Singleton()
+ static getInstance()
// Other useful Singleton methods...
Note:: A class implementing the Singleton Pattern is more than a Singleton; it
is a general purpose class with its own set of data and methods
public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
// other useful instance variables here
private Singleton() {}
public static Singleton getInstance() {
return uniqueInstance;
}
}
public static void main(String[] args) {
Singleton s = Singleton.getInstance();
Singleton r = Singleton.getInstance();
System.out.println (s);
System.out.println (r);
}
run:
15db9742
15db9742
BUILD SUCCESSFUL
 Note that, the above code is this not thread safe. If you are working in multi
threaded system then you should not use above implementation.
 For most Java applications, we obviously need to ensure that the Singleton works
in the presence of multiple threads.
 Multithreading in java is a process of executing multiple threads simultaneously.
Our multithreading problems are almost fixed by making getInstance() a
synchronized method:
public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}

Contenu connexe

Tendances

Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton pattern
babak danyal
 
Presentation on Template Method Design Pattern
Presentation on Template Method Design PatternPresentation on Template Method Design Pattern
Presentation on Template Method Design Pattern
Asif Tayef
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
Richard Paul
 

Tendances (20)

Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton pattern
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Decorator Design Pattern
Decorator Design PatternDecorator Design Pattern
Decorator Design Pattern
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Java interface
Java interfaceJava interface
Java interface
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Design Pattern
Design PatternDesign Pattern
Design Pattern
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Facade Design Pattern
Facade Design PatternFacade Design Pattern
Facade Design Pattern
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Presentation on Template Method Design Pattern
Presentation on Template Method Design PatternPresentation on Template Method Design Pattern
Presentation on Template Method Design Pattern
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 

Similaire à Singleton Design Pattern - Creation Pattern

P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
Gaurav Tyagi
 

Similaire à Singleton Design Pattern - Creation Pattern (20)

Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
2 oop
2 oop2 oop
2 oop
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
 
Design Pattern with Actionscript
Design Pattern with ActionscriptDesign Pattern with Actionscript
Design Pattern with Actionscript
 
Marionette - TorontoJS
Marionette - TorontoJSMarionette - TorontoJS
Marionette - TorontoJS
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
 
Hibernate3 q&a
Hibernate3 q&aHibernate3 q&a
Hibernate3 q&a
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Sda 8
Sda   8Sda   8
Sda 8
 
What is design pattern
What is design patternWhat is design pattern
What is design pattern
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applications
 
Singleton Object Management
Singleton Object ManagementSingleton Object Management
Singleton Object Management
 

Dernier

Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 

Dernier (20)

Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
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...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 

Singleton Design Pattern - Creation Pattern

  • 1. Software Construction Design Pattern Presentation
  • 2.  Definition and types  Creational Patterns  Advantages and usage  Discuss Problem  Class diagram  Implementation  Lazy Instantiation  Easy Instantiation  Dealing with multithreading
  • 3. Singleton Design Pattern comes under “Creational Design Patterns” category. Creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation. “ ”
  • 4.  In software engineering, the singleton pattern is a software design pattern that provides the possibility to control the number of instances (mostly one) that are allowed to be made. We also receive a global point of access to it (them)  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.
  • 5.  Imagine an intersection where several roads meet, and where the cars need to ensure they do not crash into each other when crossing this intersection.  Assuming there were no traffic lights to guide them, we would need a police officer standing in the middle to direct traffic. This officer would be a real life approximation of a singleton.  The officer would receive visual queues from all roads, telling him which one is filling up the most with cars. With all this information, he would be able to decide which road to let the cars come through, and which roads to block.  This would be significantly more complex if there were several officers controlling the intersection, where they would all be receiving visual queues from the roads, would have to communicate with each other and then collectively decide which road to let traffic come from.
  • 6.  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.  When only one instance or a specific number of instances of a class are allowed.  It is used in logging, caching, web server, etc.  For database connection, because one connection is enough for most applications and too much connections can make application slow.
  • 7.  If your program needs to do logging, you may want all output to be written to one log file. That could lead to resource conflicts and errors. objectA objectB objectC loggerA loggerB loggerC LogFile.txt
  • 8.  With a singleton logger object, you don’t need to worry about several different objects trying to write to the same file, at the same time. objectA objectB objectC loggerSingleton LogFile.txt
  • 9. Singleton - static uniqueInstance // Other useful Singleton data... - Singleton() + static getInstance() // Other useful Singleton methods... Note:: A class implementing the Singleton Pattern is more than a Singleton; it is a general purpose class with its own set of data and methods
  • 10. public class Singleton { private static Singleton uniqueInstance; // other useful instance variables here private Singleton() {} public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } }
  • 11. public class Singleton { private static Singleton uniqueInstance = new Singleton(); // other useful instance variables here private Singleton() {} public static Singleton getInstance() { return uniqueInstance; } }
  • 12. public static void main(String[] args) { Singleton s = Singleton.getInstance(); Singleton r = Singleton.getInstance(); System.out.println (s); System.out.println (r); } run: 15db9742 15db9742 BUILD SUCCESSFUL
  • 13.  Note that, the above code is this not thread safe. If you are working in multi threaded system then you should not use above implementation.  For most Java applications, we obviously need to ensure that the Singleton works in the presence of multiple threads.  Multithreading in java is a process of executing multiple threads simultaneously.
  • 14. Our multithreading problems are almost fixed by making getInstance() a synchronized method: public class Singleton { private static Singleton uniqueInstance; // other useful instance variables here private Singleton() {} public static synchronized Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } }