SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Singleton Design Pattern
Presented by:
Patel Nilay (112342)
Bareja Vishal (112354)
Vaghela Sachin(112356)
Shyara haresh(1123)
Intent :-
 the singleton pattern ensures a class has only one instance , and provides
a global point of access to it. (just like a global variable, but without the
downsides.)
Motivation :-
 There are many objects we only need one of : thread pools, caches,
dialog boxes, objects that handle preferences and registry setting,
objects used for logging, and objects that act as devise drivers to
devices like printer.
 In fact, many of these types of object, if we were to instantiate
more than one we’d run into all sorts of problem like incorrect
program behavior, overuse of resources, or inconsistent results.
Singleton pattern is the solution of this problem.
Applicability :-
Use the Singleton pattern when
 There must be exactly one instance of a class, and it must be accessible to
clients from a well-known access point.
 When the sole instance should be extensible by subclassing, and clients
should be able to use an extended instance without modifying their code.
Structure :-
Participants :-
• Singleton
 defines an instance operation that lets clients access its unique instance.
 May be responsible for creating its own unique instance.
Collaborations :-
 Clients access a singleton instance solely through singleton’s instance
operation.
Consequences :-
The singleton pattern has several benefits:
 Controlled access to sole instance.
- it can have strict control over how and when clients access it.
 Reduces name space.
- it avoids polluting the name space with global variables that store sole
instances.
 Permits refinement of operations and representation.
- you can configure the application with an instance of the class you need at run
time.
 Permit a variable number of instances.
- you can use the same approach to control the number of instance that the
application uses.
Implementation :-
 OK, so how do we implement the Singleton pattern?
 We'll use a static method to allow clients to get a reference to the single
instance and we’ll use a private constructor!
public class singleton {
private static singleton uniqueInstance;
//we have a static variable to hold our one instance of the class
singleton.
private singleton() { }
// our constructor is declared private only singleton can instantiate
this class.
public static singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new singleton();
}
return uniqueInstance;
}
/*the getInstance() method gives us a way to instantiate the class and
also to return an instance of it. (this is called lazy instantiation)*/
// othere useful methods here
}
 Note that the singleton instance is only created when needed. This is called
lazy instantiation.
 What if two threads concurrently invoke the instance() method? Any
problems?
 Our multithreading woes are almost trivially fixed by making getInstance() a
synchronized method:
public class singleton{
private static singleton uniqueInstance;
private singleton() { }
public static synchronized singleton getInstance() {
if (uniqueInstance == null){
uniqueInstance = new singleton();
}
return uniqueInstance;
}
// othere useful methods here
}
Can we improve multithreading?
 Well , we have few option…
1) Do nothing if the performance of getInstance() isn’t critical to
our application
2) Move to an eagerly created instance rather than a lazily created
one
public class singleton{
private static singleton uniqueInstance = new
singleton();
private singleton() { }
public static synchronized singleton getInstance() {
return uniqueInstance;
}
}
Using this approach, we rely on the JVM to create the instance of the
singleton when class is loaded.the JVM guarantees that instance will be
created before any thread accesses the static uniqueInstance variable.
3) Use “double-checked locking” to reduce the use of synchronization in
getInstance()
 With double-checked locking, we first check to see if an instance is created, and if not, THEN
we synchronize. This way, we only synchronize the first time through, just what we want.
public class singleton{
private volatile static singleton uniqueInstance;
/* the volatile keyword ensure that multiple threads handle the uniqueInstance
variable correctly when it is being initialized to the singleton instance */
private singleton() { }
public static synchronized singleton getInstance() {
if ( uniqueInstance == null ){
synchronized (singleton.class) {
if ( uniqueInstance == null ){
uniqueInstance = new singleton();
}
}
}
return uniqueInstance;
}
}
Known Uses :-
 Example s:-
- Java.lang.Runtime,Java.awt.desktop
- Top level GUI (window/frame)
- logging
Related Patterns :-
- Abstract factory pattern
- Builder pattern
- Prototype pattern
Any Questions…?
Thanks

Weitere ähnliche Inhalte

Was ist angesagt?

Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternMudasir Qazi
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaEdureka!
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns pptmkruthika
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns pptAman Jain
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1Shahzad
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Patternsahilrk911
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan GoleChetan Gole
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternMudasir Qazi
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General IntroductionAsma CHERIF
 

Was ist angesagt? (20)

OOP java
OOP javaOOP java
OOP java
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
Adapter Pattern
Adapter PatternAdapter Pattern
Adapter Pattern
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
UML
UMLUML
UML
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | Edureka
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 

Ähnlich wie The Singleton Pattern Presentation

Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Arsen Gasparyan
 
Creational - The Singleton Design Pattern
Creational - The Singleton Design PatternCreational - The Singleton Design Pattern
Creational - The Singleton Design PatternRagibShahriar8
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
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 PatternNishith Shukla
 
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 PatternsLalit Kale
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsMichael Heron
 
Singleton class in Java
Singleton class in JavaSingleton class in Java
Singleton class in JavaRahul Sharma
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 

Ähnlich wie The Singleton Pattern Presentation (20)

Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
Creational - The Singleton Design Pattern
Creational - The Singleton Design PatternCreational - The Singleton Design Pattern
Creational - The Singleton Design Pattern
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Simple Singleton Java
Simple Singleton JavaSimple Singleton Java
Simple Singleton Java
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
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
 
Best Practices
Best PracticesBest Practices
Best Practices
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Java unit 7
Java unit 7Java unit 7
Java unit 7
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
 
Java basics
Java basicsJava basics
Java basics
 
Sda 8
Sda   8Sda   8
Sda 8
 
Singleton class in Java
Singleton class in JavaSingleton class in Java
Singleton class in Java
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Concurrency
ConcurrencyConcurrency
Concurrency
 

Mehr von JAINIK PATEL

Architecture of Mobile Computing
Architecture of Mobile ComputingArchitecture of Mobile Computing
Architecture of Mobile ComputingJAINIK PATEL
 
112321 112333 wirless application protocol
112321 112333 wirless application protocol112321 112333 wirless application protocol
112321 112333 wirless application protocolJAINIK PATEL
 

Mehr von JAINIK PATEL (7)

Facade pattern
Facade patternFacade pattern
Facade pattern
 
SMS
SMSSMS
SMS
 
Architecture of Mobile Computing
Architecture of Mobile ComputingArchitecture of Mobile Computing
Architecture of Mobile Computing
 
security issue
security issuesecurity issue
security issue
 
Mobile Computing
Mobile ComputingMobile Computing
Mobile Computing
 
112321 112333 wirless application protocol
112321 112333 wirless application protocol112321 112333 wirless application protocol
112321 112333 wirless application protocol
 
Facadepattern
FacadepatternFacadepattern
Facadepattern
 

Kürzlich hochgeladen

psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Kürzlich hochgeladen (20)

psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

The Singleton Pattern Presentation

  • 1. Singleton Design Pattern Presented by: Patel Nilay (112342) Bareja Vishal (112354) Vaghela Sachin(112356) Shyara haresh(1123)
  • 2. Intent :-  the singleton pattern ensures a class has only one instance , and provides a global point of access to it. (just like a global variable, but without the downsides.) Motivation :-  There are many objects we only need one of : thread pools, caches, dialog boxes, objects that handle preferences and registry setting, objects used for logging, and objects that act as devise drivers to devices like printer.  In fact, many of these types of object, if we were to instantiate more than one we’d run into all sorts of problem like incorrect program behavior, overuse of resources, or inconsistent results. Singleton pattern is the solution of this problem.
  • 3. Applicability :- Use the Singleton pattern when  There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.  When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code. Structure :-
  • 4. Participants :- • Singleton  defines an instance operation that lets clients access its unique instance.  May be responsible for creating its own unique instance. Collaborations :-  Clients access a singleton instance solely through singleton’s instance operation.
  • 5. Consequences :- The singleton pattern has several benefits:  Controlled access to sole instance. - it can have strict control over how and when clients access it.  Reduces name space. - it avoids polluting the name space with global variables that store sole instances.  Permits refinement of operations and representation. - you can configure the application with an instance of the class you need at run time.  Permit a variable number of instances. - you can use the same approach to control the number of instance that the application uses.
  • 6. Implementation :-  OK, so how do we implement the Singleton pattern?  We'll use a static method to allow clients to get a reference to the single instance and we’ll use a private constructor!
  • 7. public class singleton { private static singleton uniqueInstance; //we have a static variable to hold our one instance of the class singleton. private singleton() { } // our constructor is declared private only singleton can instantiate this class. public static singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new singleton(); } return uniqueInstance; } /*the getInstance() method gives us a way to instantiate the class and also to return an instance of it. (this is called lazy instantiation)*/ // othere useful methods here }
  • 8.  Note that the singleton instance is only created when needed. This is called lazy instantiation.  What if two threads concurrently invoke the instance() method? Any problems?  Our multithreading woes are almost trivially fixed by making getInstance() a synchronized method: public class singleton{ private static singleton uniqueInstance; private singleton() { } public static synchronized singleton getInstance() { if (uniqueInstance == null){ uniqueInstance = new singleton(); } return uniqueInstance; } // othere useful methods here }
  • 9. Can we improve multithreading?
  • 10.  Well , we have few option… 1) Do nothing if the performance of getInstance() isn’t critical to our application 2) Move to an eagerly created instance rather than a lazily created one public class singleton{ private static singleton uniqueInstance = new singleton(); private singleton() { } public static synchronized singleton getInstance() { return uniqueInstance; } } Using this approach, we rely on the JVM to create the instance of the singleton when class is loaded.the JVM guarantees that instance will be created before any thread accesses the static uniqueInstance variable.
  • 11. 3) Use “double-checked locking” to reduce the use of synchronization in getInstance()  With double-checked locking, we first check to see if an instance is created, and if not, THEN we synchronize. This way, we only synchronize the first time through, just what we want. public class singleton{ private volatile static singleton uniqueInstance; /* the volatile keyword ensure that multiple threads handle the uniqueInstance variable correctly when it is being initialized to the singleton instance */ private singleton() { } public static synchronized singleton getInstance() { if ( uniqueInstance == null ){ synchronized (singleton.class) { if ( uniqueInstance == null ){ uniqueInstance = new singleton(); } } } return uniqueInstance; } }
  • 12. Known Uses :-  Example s:- - Java.lang.Runtime,Java.awt.desktop - Top level GUI (window/frame) - logging Related Patterns :- - Abstract factory pattern - Builder pattern - Prototype pattern