SlideShare ist ein Scribd-Unternehmen logo
1 von 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;
}
}

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
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
 
Design pattern
Design patternDesign pattern
Design pattern
 
Abstract Factory Pattern (Example & Implementation in Java)
Abstract Factory Pattern (Example & Implementation in Java)Abstract Factory Pattern (Example & Implementation in Java)
Abstract Factory Pattern (Example & Implementation in Java)
 
Decorator Pattern
Decorator PatternDecorator Pattern
Decorator Pattern
 
Design pattern
Design patternDesign pattern
Design pattern
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | Edureka
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 
DESIGN PATTERNS: Strategy Patterns
DESIGN PATTERNS: Strategy PatternsDESIGN PATTERNS: Strategy Patterns
DESIGN PATTERNS: Strategy Patterns
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Proxy Design Pattern
Proxy Design PatternProxy Design Pattern
Proxy Design Pattern
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 

Ähnlich wie Singleton Design Pattern - Creation Pattern

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
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1Shahzad
 
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 AppKaty Slemon
 
Design Pattern with Actionscript
Design Pattern with ActionscriptDesign Pattern with Actionscript
Design Pattern with ActionscriptDaniel Swid
 
Marionette - TorontoJS
Marionette - TorontoJSMarionette - TorontoJS
Marionette - TorontoJSmatt-briggs
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design PatternsSteven Smith
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsMichael Heron
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applicationsIvano Malavolta
 

Ähnlich wie 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
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
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
 

Kürzlich hochgeladen

result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 

Kürzlich hochgeladen (20)

result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 

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; } }