SlideShare uma empresa Scribd logo
1 de 14
SINGLETON
DESIGN
PATTERN
Index
 Intent
 Structure
 Example program
 Explanation
 Participants
 Consequences
 Limitations
 Practical examples
 Intent
 Ensure a class only has one instance, and
provide a global point of access to it.
 Motivation
 It’s important for some classes to have
exactly one instance.
 Although there can be many printers in a
system, there should be only one printer
spooler.
 There should be only one file system (or file
system manager) and one window manager.
Structure
 Example program:
public class TestSingleton {
public static void main(String args[]) {
// Get a reference to the single instance of Singleton.
Singleton s = Singleton.instance();
s.setData(34);
System.out.println("First reference: " + s);
System.out.println("Singleton data value is: " +
s.getData());
// Get another reference to the Singleton.
// Is it the same object?
s = null;
s = Singleton.instance();
System.out.println("nSecond reference: " + s);
System.out.println("Singleton data value is: " +
s.getData());
} }
The test program output is as shown:
First reference:
Singleton data value is: 34
Second reference:
Singleton data value is: 34
 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?
 If invoked concurrently, two instances of the singleton
class could be created. However, this could be
prevented using the following 2 techniques:
i) Make the instance() synchronized. Synchronization
is expensive, however, and it may have a negative
impact on the performance. Moreover, it is really
only needed the first time the unique instance is
created.
ii) Do an eager instantiation of the instance rather
than a lazy instantiation. An eager class loader
loads all the classes comprising the application
code at startup. Such an implementation requires
a static initializer and is thread safe.
Singleton Participants
 Singleton - Defines an instance operation that
lets clients access its unique instance. Instance
is a class operation (static method). May be
responsible for creating its own unique
instance
 Client - Accesses a singleton instance solely
through the singleton’s instance() method.
Singleton Consequences
 Controlled access to sole instance facilitates
strict control over when and how the clients
access it.
 The singleton pattern is an improvement over
global variables.
 It may be subclassed and it is easy to configure
an instance of an application that extends the
functionality of singleton at run-time.
 More flexible than class operations.
Singleton Limitations
 The main limitation of the singleton pattern is
that it permits the creation of only one instance
of the class, while most practical applications
require multiple instances to be initialized.
 Furthermore, in case of singleton, the system
threads fight to access the single instance
thereby degrading the performance of the
application.
Examples
 Cache – The cache can be used as a singleton
object, having a global point of reference for
all future references to the cache object and the
client application uses this in-memory object.
 Configuration File – Any application has a
single point of reference through its
configuration files. Any changes to be made to
the application will have to be made via this
single configuration file.
Thank You

Mais conteúdo relacionado

Mais procurados

Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 
Gof design pattern
Gof design patternGof design pattern
Gof design patternnaveen kumar
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design patternMindfire Solutions
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaEdureka!
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternMudasir Qazi
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
Uml structural diagrams
Uml structural diagramsUml structural diagrams
Uml structural diagramsSwathy T
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 

Mais procurados (20)

Java swing
Java swingJava swing
Java swing
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | Edureka
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Struts
StrutsStruts
Struts
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Uml structural diagrams
Uml structural diagramsUml structural diagrams
Uml structural diagrams
 
Python-Encapsulation.pptx
Python-Encapsulation.pptxPython-Encapsulation.pptx
Python-Encapsulation.pptx
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
UML Diagrams
UML DiagramsUML Diagrams
UML Diagrams
 

Semelhante a Singleton design pattern

P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design PatternsSteven Smith
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Steven Smith
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Steven Smith
 
Introduction To Design Patterns
Introduction To Design PatternsIntroduction To Design Patterns
Introduction To Design Patternssukumarraju6
 
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
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patternsamitarcade
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Arsen Gasparyan
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton patternbabak danyal
 
ActionScript Design Patterns
ActionScript Design Patterns ActionScript Design Patterns
ActionScript Design Patterns Yoss Cohen
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptxSajidTk2
 
Creational - The Singleton Design Pattern
Creational - The Singleton Design PatternCreational - The Singleton Design Pattern
Creational - The Singleton Design PatternRagibShahriar8
 
Review oop and ood
Review oop and oodReview oop and ood
Review oop and oodthan sare
 

Semelhante a Singleton design pattern (20)

P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
Introduction To Design Patterns
Introduction To Design PatternsIntroduction To Design Patterns
Introduction To 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
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
Singletons
SingletonsSingletons
Singletons
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton pattern
 
ActionScript Design Patterns
ActionScript Design Patterns ActionScript Design Patterns
ActionScript Design Patterns
 
Sda 8
Sda   8Sda   8
Sda 8
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptx
 
Creational - The Singleton Design Pattern
Creational - The Singleton Design PatternCreational - The Singleton Design Pattern
Creational - The Singleton Design Pattern
 
Review oop and ood
Review oop and oodReview oop and ood
Review oop and ood
 
Code Quality Management iOS
Code Quality Management iOSCode Quality Management iOS
Code Quality Management iOS
 

Último

Kondapur ] High Profile Call Girls in Hyderabad (Adult Only) 9352988975 Escor...
Kondapur ] High Profile Call Girls in Hyderabad (Adult Only) 9352988975 Escor...Kondapur ] High Profile Call Girls in Hyderabad (Adult Only) 9352988975 Escor...
Kondapur ] High Profile Call Girls in Hyderabad (Adult Only) 9352988975 Escor...manjugarg389
 
一比一原版(ANU毕业证书)澳大利亚国立大学毕业证原件一模一样
一比一原版(ANU毕业证书)澳大利亚国立大学毕业证原件一模一样一比一原版(ANU毕业证书)澳大利亚国立大学毕业证原件一模一样
一比一原版(ANU毕业证书)澳大利亚国立大学毕业证原件一模一样yhavx
 
Top profile Call Girls In Mau [ 7014168258 ] Call Me For Genuine Models We ar...
Top profile Call Girls In Mau [ 7014168258 ] Call Me For Genuine Models We ar...Top profile Call Girls In Mau [ 7014168258 ] Call Me For Genuine Models We ar...
Top profile Call Girls In Mau [ 7014168258 ] Call Me For Genuine Models We ar...nirzagarg
 
Top profile Call Girls In fatehgarh [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In fatehgarh [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In fatehgarh [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In fatehgarh [ 7014168258 ] Call Me For Genuine Models...gajnagarg
 
Raebareli Girl Whatsapp Number 📞 8617370543 | Girls Number for Friendship
Raebareli Girl Whatsapp Number 📞 8617370543 | Girls Number for FriendshipRaebareli Girl Whatsapp Number 📞 8617370543 | Girls Number for Friendship
Raebareli Girl Whatsapp Number 📞 8617370543 | Girls Number for FriendshipNitya salvi
 
Mohanlalganj ! Call Girls in Lucknow - 450+ Call Girl Cash Payment 9548273370...
Mohanlalganj ! Call Girls in Lucknow - 450+ Call Girl Cash Payment 9548273370...Mohanlalganj ! Call Girls in Lucknow - 450+ Call Girl Cash Payment 9548273370...
Mohanlalganj ! Call Girls in Lucknow - 450+ Call Girl Cash Payment 9548273370...gargpaaro
 
How to Create a Productive Workspace Trends and Tips.pdf
How to Create a Productive Workspace Trends and Tips.pdfHow to Create a Productive Workspace Trends and Tips.pdf
How to Create a Productive Workspace Trends and Tips.pdfOffice Furniture Plus - Irving
 
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证wpkuukw
 
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...gajnagarg
 
The hottest UI and UX Design Trends 2024
The hottest UI and UX Design Trends 2024The hottest UI and UX Design Trends 2024
The hottest UI and UX Design Trends 2024Ilham Brata
 
怎样办理伯明翰大学学院毕业证(Birmingham毕业证书)成绩单留信认证
怎样办理伯明翰大学学院毕业证(Birmingham毕业证书)成绩单留信认证怎样办理伯明翰大学学院毕业证(Birmingham毕业证书)成绩单留信认证
怎样办理伯明翰大学学院毕业证(Birmingham毕业证书)成绩单留信认证eeanqy
 
Pondicherry Escorts Service Girl ^ 9332606886, WhatsApp Anytime Pondicherry
Pondicherry Escorts Service Girl ^ 9332606886, WhatsApp Anytime PondicherryPondicherry Escorts Service Girl ^ 9332606886, WhatsApp Anytime Pondicherry
Pondicherry Escorts Service Girl ^ 9332606886, WhatsApp Anytime Pondicherrymeghakumariji156
 
High Profile Escorts Nerul WhatsApp +91-9930687706, Best Service
High Profile Escorts Nerul WhatsApp +91-9930687706, Best ServiceHigh Profile Escorts Nerul WhatsApp +91-9930687706, Best Service
High Profile Escorts Nerul WhatsApp +91-9930687706, Best Servicemeghakumariji156
 
Sweety Planet Packaging Design Process Book.pptx
Sweety Planet Packaging Design Process Book.pptxSweety Planet Packaging Design Process Book.pptx
Sweety Planet Packaging Design Process Book.pptxbingyichin04
 
Q4-W4-SCIENCE-5 power point presentation
Q4-W4-SCIENCE-5 power point presentationQ4-W4-SCIENCE-5 power point presentation
Q4-W4-SCIENCE-5 power point presentationZenSeloveres
 
Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...
Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...
Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...HyderabadDolls
 
一比一定(购)滑铁卢大学毕业证(UW毕业证)成绩单学位证
一比一定(购)滑铁卢大学毕业证(UW毕业证)成绩单学位证一比一定(购)滑铁卢大学毕业证(UW毕业证)成绩单学位证
一比一定(购)滑铁卢大学毕业证(UW毕业证)成绩单学位证wpkuukw
 
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...HyderabadDolls
 
Essential UI/UX Design Principles: A Comprehensive Guide
Essential UI/UX Design Principles: A Comprehensive GuideEssential UI/UX Design Principles: A Comprehensive Guide
Essential UI/UX Design Principles: A Comprehensive GuideDesign Studio UI UX
 

Último (20)

Kondapur ] High Profile Call Girls in Hyderabad (Adult Only) 9352988975 Escor...
Kondapur ] High Profile Call Girls in Hyderabad (Adult Only) 9352988975 Escor...Kondapur ] High Profile Call Girls in Hyderabad (Adult Only) 9352988975 Escor...
Kondapur ] High Profile Call Girls in Hyderabad (Adult Only) 9352988975 Escor...
 
一比一原版(ANU毕业证书)澳大利亚国立大学毕业证原件一模一样
一比一原版(ANU毕业证书)澳大利亚国立大学毕业证原件一模一样一比一原版(ANU毕业证书)澳大利亚国立大学毕业证原件一模一样
一比一原版(ANU毕业证书)澳大利亚国立大学毕业证原件一模一样
 
Top profile Call Girls In Mau [ 7014168258 ] Call Me For Genuine Models We ar...
Top profile Call Girls In Mau [ 7014168258 ] Call Me For Genuine Models We ar...Top profile Call Girls In Mau [ 7014168258 ] Call Me For Genuine Models We ar...
Top profile Call Girls In Mau [ 7014168258 ] Call Me For Genuine Models We ar...
 
Top profile Call Girls In fatehgarh [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In fatehgarh [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In fatehgarh [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In fatehgarh [ 7014168258 ] Call Me For Genuine Models...
 
Raebareli Girl Whatsapp Number 📞 8617370543 | Girls Number for Friendship
Raebareli Girl Whatsapp Number 📞 8617370543 | Girls Number for FriendshipRaebareli Girl Whatsapp Number 📞 8617370543 | Girls Number for Friendship
Raebareli Girl Whatsapp Number 📞 8617370543 | Girls Number for Friendship
 
Mohanlalganj ! Call Girls in Lucknow - 450+ Call Girl Cash Payment 9548273370...
Mohanlalganj ! Call Girls in Lucknow - 450+ Call Girl Cash Payment 9548273370...Mohanlalganj ! Call Girls in Lucknow - 450+ Call Girl Cash Payment 9548273370...
Mohanlalganj ! Call Girls in Lucknow - 450+ Call Girl Cash Payment 9548273370...
 
How to Create a Productive Workspace Trends and Tips.pdf
How to Create a Productive Workspace Trends and Tips.pdfHow to Create a Productive Workspace Trends and Tips.pdf
How to Create a Productive Workspace Trends and Tips.pdf
 
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证
 
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...
 
The hottest UI and UX Design Trends 2024
The hottest UI and UX Design Trends 2024The hottest UI and UX Design Trends 2024
The hottest UI and UX Design Trends 2024
 
怎样办理伯明翰大学学院毕业证(Birmingham毕业证书)成绩单留信认证
怎样办理伯明翰大学学院毕业证(Birmingham毕业证书)成绩单留信认证怎样办理伯明翰大学学院毕业证(Birmingham毕业证书)成绩单留信认证
怎样办理伯明翰大学学院毕业证(Birmingham毕业证书)成绩单留信认证
 
Pondicherry Escorts Service Girl ^ 9332606886, WhatsApp Anytime Pondicherry
Pondicherry Escorts Service Girl ^ 9332606886, WhatsApp Anytime PondicherryPondicherry Escorts Service Girl ^ 9332606886, WhatsApp Anytime Pondicherry
Pondicherry Escorts Service Girl ^ 9332606886, WhatsApp Anytime Pondicherry
 
Hackathon evaluation template_latest_uploadpdf
Hackathon evaluation template_latest_uploadpdfHackathon evaluation template_latest_uploadpdf
Hackathon evaluation template_latest_uploadpdf
 
High Profile Escorts Nerul WhatsApp +91-9930687706, Best Service
High Profile Escorts Nerul WhatsApp +91-9930687706, Best ServiceHigh Profile Escorts Nerul WhatsApp +91-9930687706, Best Service
High Profile Escorts Nerul WhatsApp +91-9930687706, Best Service
 
Sweety Planet Packaging Design Process Book.pptx
Sweety Planet Packaging Design Process Book.pptxSweety Planet Packaging Design Process Book.pptx
Sweety Planet Packaging Design Process Book.pptx
 
Q4-W4-SCIENCE-5 power point presentation
Q4-W4-SCIENCE-5 power point presentationQ4-W4-SCIENCE-5 power point presentation
Q4-W4-SCIENCE-5 power point presentation
 
Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...
Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...
Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...
 
一比一定(购)滑铁卢大学毕业证(UW毕业证)成绩单学位证
一比一定(购)滑铁卢大学毕业证(UW毕业证)成绩单学位证一比一定(购)滑铁卢大学毕业证(UW毕业证)成绩单学位证
一比一定(购)滑铁卢大学毕业证(UW毕业证)成绩单学位证
 
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...
 
Essential UI/UX Design Principles: A Comprehensive Guide
Essential UI/UX Design Principles: A Comprehensive GuideEssential UI/UX Design Principles: A Comprehensive Guide
Essential UI/UX Design Principles: A Comprehensive Guide
 

Singleton design pattern

  • 2. Index  Intent  Structure  Example program  Explanation  Participants  Consequences  Limitations  Practical examples
  • 3.  Intent  Ensure a class only has one instance, and provide a global point of access to it.  Motivation  It’s important for some classes to have exactly one instance.  Although there can be many printers in a system, there should be only one printer spooler.  There should be only one file system (or file system manager) and one window manager.
  • 5.  Example program: public class TestSingleton { public static void main(String args[]) { // Get a reference to the single instance of Singleton. Singleton s = Singleton.instance(); s.setData(34); System.out.println("First reference: " + s); System.out.println("Singleton data value is: " + s.getData());
  • 6. // Get another reference to the Singleton. // Is it the same object? s = null; s = Singleton.instance(); System.out.println("nSecond reference: " + s); System.out.println("Singleton data value is: " + s.getData()); } }
  • 7. The test program output is as shown: First reference: Singleton data value is: 34 Second reference: Singleton data value is: 34
  • 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?  If invoked concurrently, two instances of the singleton class could be created. However, this could be prevented using the following 2 techniques: i) Make the instance() synchronized. Synchronization is expensive, however, and it may have a negative impact on the performance. Moreover, it is really only needed the first time the unique instance is created.
  • 9. ii) Do an eager instantiation of the instance rather than a lazy instantiation. An eager class loader loads all the classes comprising the application code at startup. Such an implementation requires a static initializer and is thread safe.
  • 10. Singleton Participants  Singleton - Defines an instance operation that lets clients access its unique instance. Instance is a class operation (static method). May be responsible for creating its own unique instance  Client - Accesses a singleton instance solely through the singleton’s instance() method.
  • 11. Singleton Consequences  Controlled access to sole instance facilitates strict control over when and how the clients access it.  The singleton pattern is an improvement over global variables.  It may be subclassed and it is easy to configure an instance of an application that extends the functionality of singleton at run-time.  More flexible than class operations.
  • 12. Singleton Limitations  The main limitation of the singleton pattern is that it permits the creation of only one instance of the class, while most practical applications require multiple instances to be initialized.  Furthermore, in case of singleton, the system threads fight to access the single instance thereby degrading the performance of the application.
  • 13. Examples  Cache – The cache can be used as a singleton object, having a global point of reference for all future references to the cache object and the client application uses this in-memory object.  Configuration File – Any application has a single point of reference through its configuration files. Any changes to be made to the application will have to be made via this single configuration file.