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

More Related Content

What's hot

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
 
Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General IntroductionAsma CHERIF
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternMudasir Qazi
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaEdureka!
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsMichael Heron
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory 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
Design PatternsDesign Patterns
Design Patternssoms_1
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan GoleChetan Gole
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design PatternKanushka Gayan
 
Design pattern & categories
Design pattern & categoriesDesign pattern & categories
Design pattern & categoriesHimanshu
 

What's hot (20)

Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method 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)
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | Edureka
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Design pattern & categories
Design pattern & categoriesDesign pattern & categories
Design pattern & categories
 

Similar to 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
 

Similar to 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
 

Recently uploaded

NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...
NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...
NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...Amil baba
 
Design Portofolios - Licensed Architect / BIM Specialist
Design Portofolios - Licensed Architect / BIM SpecialistDesign Portofolios - Licensed Architect / BIM Specialist
Design Portofolios - Licensed Architect / BIM SpecialistYudistira
 
Abdulaziz Tariq Abdulaziz Mustafa CV 2024
Abdulaziz Tariq Abdulaziz Mustafa CV 2024Abdulaziz Tariq Abdulaziz Mustafa CV 2024
Abdulaziz Tariq Abdulaziz Mustafa CV 2024Abdulaziz Mustafa
 
如何办理(Bath毕业证书)巴斯大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(Bath毕业证书)巴斯大学毕业证成绩单本科硕士学位证留信学历认证如何办理(Bath毕业证书)巴斯大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(Bath毕业证书)巴斯大学毕业证成绩单本科硕士学位证留信学历认证ugzga
 
And that's about to change! (Service Design Drinks Berlin May 2024)
And that's about to change! (Service Design Drinks Berlin May 2024)And that's about to change! (Service Design Drinks Berlin May 2024)
And that's about to change! (Service Design Drinks Berlin May 2024)☕ 🥧 🚲 Martin Gude
 
如何办理(RUG毕业证书)格罗宁根大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(RUG毕业证书)格罗宁根大学毕业证成绩单本科硕士学位证留信学历认证如何办理(RUG毕业证书)格罗宁根大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(RUG毕业证书)格罗宁根大学毕业证成绩单本科硕士学位证留信学历认证ugzga
 
Naer VR: Advanced Research and Usability Testing Project
Naer VR: Advanced Research and Usability Testing ProjectNaer VR: Advanced Research and Usability Testing Project
Naer VR: Advanced Research and Usability Testing Projectbuvanatest
 
Week of Action 2022_EIT Climate-KIC_Headers
Week of Action 2022_EIT Climate-KIC_HeadersWeek of Action 2022_EIT Climate-KIC_Headers
Week of Action 2022_EIT Climate-KIC_Headersekinlvnt
 
Evaluating natural frequencies and mode shapes.pptx
Evaluating natural frequencies and mode shapes.pptxEvaluating natural frequencies and mode shapes.pptx
Evaluating natural frequencies and mode shapes.pptxjoshuaclack73
 
The Journey of Fashion Designer Sketches - From Concept to Catwalk
The Journey of Fashion Designer Sketches - From Concept to CatwalkThe Journey of Fashion Designer Sketches - From Concept to Catwalk
The Journey of Fashion Designer Sketches - From Concept to CatwalkWave PLM
 
Top 10 Website Designing Hacks for Beginners.pptx.pptx
Top 10 Website Designing Hacks for Beginners.pptx.pptxTop 10 Website Designing Hacks for Beginners.pptx.pptx
Top 10 Website Designing Hacks for Beginners.pptx.pptxe-Definers Technology
 
Presentation on 3D Printing.pptx presentation
Presentation on 3D Printing.pptx presentationPresentation on 3D Printing.pptx presentation
Presentation on 3D Printing.pptx presentationajroy0196
 
Heidi Livengood's Professional CADD Portfolio
Heidi Livengood's Professional CADD PortfolioHeidi Livengood's Professional CADD Portfolio
Heidi Livengood's Professional CADD PortfolioHeidiLivengood
 
Recycled Modular Low Cost Construction .pdf
Recycled Modular Low Cost Construction .pdfRecycled Modular Low Cost Construction .pdf
Recycled Modular Low Cost Construction .pdfjeffreycarroll14
 
The Impact of Artificial Intelligence on Modern Healthcare.pptx
The Impact of Artificial Intelligence on Modern Healthcare.pptxThe Impact of Artificial Intelligence on Modern Healthcare.pptx
The Impact of Artificial Intelligence on Modern Healthcare.pptxDoraemon495609
 
Explaining the Hidden Treasures of Modern Bathroom Design — freixadesign.pdf
Explaining the Hidden Treasures of Modern Bathroom Design — freixadesign.pdfExplaining the Hidden Treasures of Modern Bathroom Design — freixadesign.pdf
Explaining the Hidden Treasures of Modern Bathroom Design — freixadesign.pdfFreixa Home Design
 
Mark Zuckerberg Carthago Delenda Est Shirt
Mark Zuckerberg Carthago Delenda Est ShirtMark Zuckerberg Carthago Delenda Est Shirt
Mark Zuckerberg Carthago Delenda Est ShirtMHBijoy3
 
Onyx Tiles Where Elegance Meets Durability
Onyx Tiles Where Elegance Meets DurabilityOnyx Tiles Where Elegance Meets Durability
Onyx Tiles Where Elegance Meets DurabilityTracy Lipscomb
 
Real Smart Art Infographics by Slidesgo.pptx
Real Smart Art Infographics by Slidesgo.pptxReal Smart Art Infographics by Slidesgo.pptx
Real Smart Art Infographics by Slidesgo.pptxArindamMookherji1
 
100^%)( MAYIBUYE))(*((+27838792658))*))௹ )Abortion Pills for Sale in Soweto, ...
100^%)( MAYIBUYE))(*((+27838792658))*))௹ )Abortion Pills for Sale in Soweto, ...100^%)( MAYIBUYE))(*((+27838792658))*))௹ )Abortion Pills for Sale in Soweto, ...
100^%)( MAYIBUYE))(*((+27838792658))*))௹ )Abortion Pills for Sale in Soweto, ...drjose256
 

Recently uploaded (20)

NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...
NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...
NO1 Best Kala Jadu Expert Specialist In Qatar Kala Jadu Expert Specialist In ...
 
Design Portofolios - Licensed Architect / BIM Specialist
Design Portofolios - Licensed Architect / BIM SpecialistDesign Portofolios - Licensed Architect / BIM Specialist
Design Portofolios - Licensed Architect / BIM Specialist
 
Abdulaziz Tariq Abdulaziz Mustafa CV 2024
Abdulaziz Tariq Abdulaziz Mustafa CV 2024Abdulaziz Tariq Abdulaziz Mustafa CV 2024
Abdulaziz Tariq Abdulaziz Mustafa CV 2024
 
如何办理(Bath毕业证书)巴斯大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(Bath毕业证书)巴斯大学毕业证成绩单本科硕士学位证留信学历认证如何办理(Bath毕业证书)巴斯大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(Bath毕业证书)巴斯大学毕业证成绩单本科硕士学位证留信学历认证
 
And that's about to change! (Service Design Drinks Berlin May 2024)
And that's about to change! (Service Design Drinks Berlin May 2024)And that's about to change! (Service Design Drinks Berlin May 2024)
And that's about to change! (Service Design Drinks Berlin May 2024)
 
如何办理(RUG毕业证书)格罗宁根大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(RUG毕业证书)格罗宁根大学毕业证成绩单本科硕士学位证留信学历认证如何办理(RUG毕业证书)格罗宁根大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(RUG毕业证书)格罗宁根大学毕业证成绩单本科硕士学位证留信学历认证
 
Naer VR: Advanced Research and Usability Testing Project
Naer VR: Advanced Research and Usability Testing ProjectNaer VR: Advanced Research and Usability Testing Project
Naer VR: Advanced Research and Usability Testing Project
 
Week of Action 2022_EIT Climate-KIC_Headers
Week of Action 2022_EIT Climate-KIC_HeadersWeek of Action 2022_EIT Climate-KIC_Headers
Week of Action 2022_EIT Climate-KIC_Headers
 
Evaluating natural frequencies and mode shapes.pptx
Evaluating natural frequencies and mode shapes.pptxEvaluating natural frequencies and mode shapes.pptx
Evaluating natural frequencies and mode shapes.pptx
 
The Journey of Fashion Designer Sketches - From Concept to Catwalk
The Journey of Fashion Designer Sketches - From Concept to CatwalkThe Journey of Fashion Designer Sketches - From Concept to Catwalk
The Journey of Fashion Designer Sketches - From Concept to Catwalk
 
Top 10 Website Designing Hacks for Beginners.pptx.pptx
Top 10 Website Designing Hacks for Beginners.pptx.pptxTop 10 Website Designing Hacks for Beginners.pptx.pptx
Top 10 Website Designing Hacks for Beginners.pptx.pptx
 
Presentation on 3D Printing.pptx presentation
Presentation on 3D Printing.pptx presentationPresentation on 3D Printing.pptx presentation
Presentation on 3D Printing.pptx presentation
 
Heidi Livengood's Professional CADD Portfolio
Heidi Livengood's Professional CADD PortfolioHeidi Livengood's Professional CADD Portfolio
Heidi Livengood's Professional CADD Portfolio
 
Recycled Modular Low Cost Construction .pdf
Recycled Modular Low Cost Construction .pdfRecycled Modular Low Cost Construction .pdf
Recycled Modular Low Cost Construction .pdf
 
The Impact of Artificial Intelligence on Modern Healthcare.pptx
The Impact of Artificial Intelligence on Modern Healthcare.pptxThe Impact of Artificial Intelligence on Modern Healthcare.pptx
The Impact of Artificial Intelligence on Modern Healthcare.pptx
 
Explaining the Hidden Treasures of Modern Bathroom Design — freixadesign.pdf
Explaining the Hidden Treasures of Modern Bathroom Design — freixadesign.pdfExplaining the Hidden Treasures of Modern Bathroom Design — freixadesign.pdf
Explaining the Hidden Treasures of Modern Bathroom Design — freixadesign.pdf
 
Mark Zuckerberg Carthago Delenda Est Shirt
Mark Zuckerberg Carthago Delenda Est ShirtMark Zuckerberg Carthago Delenda Est Shirt
Mark Zuckerberg Carthago Delenda Est Shirt
 
Onyx Tiles Where Elegance Meets Durability
Onyx Tiles Where Elegance Meets DurabilityOnyx Tiles Where Elegance Meets Durability
Onyx Tiles Where Elegance Meets Durability
 
Real Smart Art Infographics by Slidesgo.pptx
Real Smart Art Infographics by Slidesgo.pptxReal Smart Art Infographics by Slidesgo.pptx
Real Smart Art Infographics by Slidesgo.pptx
 
100^%)( MAYIBUYE))(*((+27838792658))*))௹ )Abortion Pills for Sale in Soweto, ...
100^%)( MAYIBUYE))(*((+27838792658))*))௹ )Abortion Pills for Sale in Soweto, ...100^%)( MAYIBUYE))(*((+27838792658))*))௹ )Abortion Pills for Sale in Soweto, ...
100^%)( MAYIBUYE))(*((+27838792658))*))௹ )Abortion Pills for Sale in Soweto, ...
 

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.