SlideShare a Scribd company logo
The Perks and Perils of the Singleton Design Pattern
Singleton
The Perks and Perils of the Singleton Design Pattern
Motivation
You have that one, and exactly one object:
â—Ź Database connection
â—Ź Hardware interface
● …
and you have to make sure all parts of the application use
that one and only object
Solution
Head up to that class, and:
â—Ź Restrict the class to create only one object
â—Ź Provide global access to it
Ref: [1]
Example Single Instance
Global Access
Use it anywhere
View 1
View 2
Users Store
Some object
Example - Diagram
Example - Even more!
View 1
View 2
View 3
Users Store
Departments
Store
Singletons
(DB /
Backend)
Connection
Techniques
Lazy initialization
Ref: [2]
Techniques 2
Synchronized lazy initialization
Clearer, but lower concurrency
Higher concurrency
Ref: [2]
Techniques - 3
Eager initialization
No need for synchronization
Ref: [2]
Benefits
â—Ź State shared globally as required
â—Ź Global access; No complications to object access
â—Ź The object handles its own creation logic
â—Ź Hide details of the Singleton
â—Ź Can be used to implement some other patterns as well
○ Abstract Factory, Builder, Prototype …
The end
Not really!
Singleton as an anti-pattern
Singleton is popular because:
â—Ź It was included in GoF Design Patterns
● It’s easy; the easiest in the book
People started a rebellion:
â—Ź Any design pattern can be abused, except for Singleton
â—Ź Valid motive, but ruins everything with its two steps
Ref: [3, 10]
Glorified Global Variables
Have a bug? Now go over all those files for a clue!
Mutable
state
1
This one
caused the
bug
2
This one
found it
Ref: [4]
Glorified Global Variables
When some code uses a global variable, it’s harder to
reason about it
Mutable
state
1
To know what this
object / function is
doing
2
You also
need to
understand
what this is
doing
Ref: [4]
Lifecycle
The Singleton controls its own creation and lifecycle
â—Ź Violation of SRP:
â—‹ Connecting to database is a responsibility
â—‹ Creating, opening and closing the connection are other
responsibilities
â—Ź Resetting the state is harder and more error-prone
than creating a new object
Ref: [3, 5]
Lifecycle
â—Ź Now you have to make all
Singletons reset to initial state
â—Ź You have to wait to reset
properly
â—‹ Sync data
â—‹ Clear cache
Lifecycle
● The user’s signed-in session is shorter than the
application’s lifecycle.
â—Ź A global state, if necessary, should only handle states
that last for the entire application’s complete lifecycle
Ref: [5]
Hiding Dependencies
● You don’t know what that Singleton needs
○ Singleton.getInstance() doesn’t explain much
Data List Singleton
What you see
Data List Singleton
What it actually is
Connection Authenticator
User
Ref: [3]
Hiding Dependencies - Example
â—Ź Only works when you run as
part of the suite.
â—Ź When run in isolation,
throws
NullPointerException.
Ref: [3]
Hiding Dependencies - Example
â—Ź You ask a senior, and he tells
you that CreditCardProcessor
needs to be handled first
â—Ź Still, it throws an exception
Ref: [3]
Hiding Dependencies - Example
â—Ź You ask more. Now you know
that both Database and
OfflineQueue need to be
initialized first
â—Ź The code worked!
â—Ź Now your bank account only
has $12.5 because this code
charged you for $100
Must be done
in the same
order!
Ref: [3]
â—Ź The code is not stable, if Database gets modified,
other classes may fail
○ Because you don’t know what depends on Database and how
â—Ź The code is not flexible, anything that depends on a
Singleton is hard wired to that Singleton
● You can’t unit test a class without the Singleton
initialized
● You can’t use mock objects for testing
Hiding Dependencies
Ref: [3]
Encourage Coupling
● Since it’s global, any class anywhere can get it easily
â—Ź If the developer is thinking hard how to get it in that
class, he would think if that class should get it
Coupling between SomeTransaction
and MySQLConnection
Ref: [4]
Encourage Coupling
â—Ź Now, you need to use a NoSQL database along with the
SQL one
â—Ź SomeTransaction should switch to NoSQL database
SomeTransaction
MongoDBConnection
MySQLConnectionTightly coupled
Remove the coupling
between
SomeTransaction and
MySQLConnection first
Limiting Instantiation
Are you really sure you won’t need another object of that
Singleton class?
nobacks.com
SingletonScreen
We only need
one object for
that one screen
nobacks.com
So what happens when I plug
that screen to the laptop?
Big deal!
I don’t care if they’re bad or not.
I only use one or two Singletons,
what’s going to happen anyway?
Source
That’s the real problem!
This one or two Singletons are strangling all or most of
classes
â—‹ Many classes are tightly coupled to it
○ Many classes can’t be tested properly
â—‹ Change something in that Singleton and all other classes need
to be changed as well
The Root of the Problem
This part is
very
legitimate!
This is
not
Ref: [9]
Solution
● Pass it a.k.a “Inject it!”
â—Ź Get it from somewhere already global
â—‹ That place is responsible for creating it and managing its
lifecycle
â—‹ There are some evils that we can only reduce, but can never
eliminate, like global state
Ref: [7]
Example
A whole bunch of singletons
Ref: [7]
Example
new OfflineQueue(database)
Ref: [7]
Example
● We’re sure that only one object is being used
â—Ź Dependencies are declared
â—Ź Dependencies are passed
â—Ź Each class is testable and mockable
● “Creation” is the factory’s responsibility
● If you ever need to have a new database, you don’t
have to modify available classes
Ref: [7]
Immutable State Singletons
Immutable state Singletons, enums in Java, objects in
Scala, … are okay
But still, be aware of coupling, limiting classes from
inheritance, hiding dependencies …
Ref: [9]
References
1. c2.com: Singleton
2. Wikipedia
3. SO: What's so bad about singletons
4. gameprogrammingpatterns.com
5. Avoiding Singleton Abuse
6. programmers.stackexchange: So singletons are bad then what
7. Singletons are pathological liars
8. Where have all the singletons gone
9. Root cause of singletons
10. Singletons considered stupid
Questions?

More Related Content

Viewers also liked (13)

PPTX
Webquest
coreysick
 
PPTX
Unidad iii estrategias didacticas
Ines Haydee Figueredo Chacin
 
ODP
Tema 4 los seres vivos
pgp3
 
PPTX
Las tic nadia liliana mina bedoya.pptx28
nadialilianaminabedoya
 
PDF
Cuandotodopareceperdido
yolis0223
 
PDF
Pristolepis pentacantha, a new species
Mathews Plamoottil
 
PPTX
InvestigaciĂłn Cuantitativa
Aracely Castillo
 
PPTX
Central asia adventure tours
AsiaAdventures
 
PPTX
Antibody Aducanumab Reduces Αβ Plaques in Alzheimer’s Disease
Riaz Rahman
 
PDF
InnoVision Fall 2016
Sarah Berry
 
ODP
Mi semana de nuevas tecnologias!!
FELIPE MENDO LÓPEZ
 
PDF
CORPORATE_MIPCOM
Kostas METAXAS
 
PPT
Tutorial Viadeo
Quiero empleo Burgos
 
Webquest
coreysick
 
Unidad iii estrategias didacticas
Ines Haydee Figueredo Chacin
 
Tema 4 los seres vivos
pgp3
 
Las tic nadia liliana mina bedoya.pptx28
nadialilianaminabedoya
 
Cuandotodopareceperdido
yolis0223
 
Pristolepis pentacantha, a new species
Mathews Plamoottil
 
InvestigaciĂłn Cuantitativa
Aracely Castillo
 
Central asia adventure tours
AsiaAdventures
 
Antibody Aducanumab Reduces Αβ Plaques in Alzheimer’s Disease
Riaz Rahman
 
InnoVision Fall 2016
Sarah Berry
 
Mi semana de nuevas tecnologias!!
FELIPE MENDO LÓPEZ
 
CORPORATE_MIPCOM
Kostas METAXAS
 
Tutorial Viadeo
Quiero empleo Burgos
 

Similar to The Perks and Perils of the Singleton Design Pattern (20)

PDF
Android Frameworks: Highlighting the Need for a Solid Development Framework 
Mutual Mobile
 
PPTX
Why Concurrency is hard ?
Ramith Jayasinghe
 
PPTX
Concurrency - Why it's hard ?
Ramith Jayasinghe
 
PDF
cf.Objective() 2017 - Design patterns - Brad Wood
Ortus Solutions, Corp
 
KEY
Mac/iOS Design Patterns
Robert Brown
 
PDF
Handling Lifecycles in a Jetpack way
Han Yin
 
PPT
Design_Patterns_Dr.CM.ppt
C Meenakshi Meyyappan
 
PDF
Making Strongly-typed NETCONF Usable
Open Networking Summit
 
PPTX
Why React's Awesome!
nomanalikk
 
PDF
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Grzegorz Miejski
 
PDF
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
PPT
10-design-patterns1.ppt.software engineering
ArwaBohra6
 
PPTX
UNIT IV DESIGN PATTERNS.pptx
anguraju1
 
PDF
Async Web Frameworks in Python
Ryan Johnson
 
PPTX
O365 Developer Bootcamp NJ 2018 - Material
Thomas Daly
 
PDF
Angular2 with type script
Ravi Mone
 
PDF
Create first android app with MVVM Architecture
khushbu thakker
 
PDF
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
Codemotion
 
PDF
Angular Rebooted: Components Everywhere
Carlo Bonamico
 
PPTX
Frontend training
Adrian Caetano
 
Android Frameworks: Highlighting the Need for a Solid Development Framework 
Mutual Mobile
 
Why Concurrency is hard ?
Ramith Jayasinghe
 
Concurrency - Why it's hard ?
Ramith Jayasinghe
 
cf.Objective() 2017 - Design patterns - Brad Wood
Ortus Solutions, Corp
 
Mac/iOS Design Patterns
Robert Brown
 
Handling Lifecycles in a Jetpack way
Han Yin
 
Design_Patterns_Dr.CM.ppt
C Meenakshi Meyyappan
 
Making Strongly-typed NETCONF Usable
Open Networking Summit
 
Why React's Awesome!
nomanalikk
 
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Grzegorz Miejski
 
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
10-design-patterns1.ppt.software engineering
ArwaBohra6
 
UNIT IV DESIGN PATTERNS.pptx
anguraju1
 
Async Web Frameworks in Python
Ryan Johnson
 
O365 Developer Bootcamp NJ 2018 - Material
Thomas Daly
 
Angular2 with type script
Ravi Mone
 
Create first android app with MVVM Architecture
khushbu thakker
 
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
Codemotion
 
Angular Rebooted: Components Everywhere
Carlo Bonamico
 
Frontend training
Adrian Caetano
 
Ad

More from BADR (15)

PDF
Sunspot - The Ruby Way into Solr
BADR
 
PDF
Docker up and Running For Web Developers
BADR
 
PDF
Vue.js
BADR
 
PDF
There and Back Again - A Tale of Programming Languages
BADR
 
PDF
Take Pride in Your Code - Test-Driven Development
BADR
 
PDF
Single Responsibility Principle
BADR
 
PDF
NoSQL Databases
BADR
 
PDF
Explicit Semantic Analysis
BADR
 
PDF
Getting some Git
BADR
 
PDF
ReactiveX
BADR
 
PDF
Algorithms - A Sneak Peek
BADR
 
PDF
Android from A to Z
BADR
 
PDF
Apache Hadoop - Big Data Engineering
BADR
 
PDF
MySQL Indexing
BADR
 
PDF
Duckville - The Strategy Design Pattern
BADR
 
Sunspot - The Ruby Way into Solr
BADR
 
Docker up and Running For Web Developers
BADR
 
Vue.js
BADR
 
There and Back Again - A Tale of Programming Languages
BADR
 
Take Pride in Your Code - Test-Driven Development
BADR
 
Single Responsibility Principle
BADR
 
NoSQL Databases
BADR
 
Explicit Semantic Analysis
BADR
 
Getting some Git
BADR
 
ReactiveX
BADR
 
Algorithms - A Sneak Peek
BADR
 
Android from A to Z
BADR
 
Apache Hadoop - Big Data Engineering
BADR
 
MySQL Indexing
BADR
 
Duckville - The Strategy Design Pattern
BADR
 
Ad

Recently uploaded (20)

PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PDF
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
PDF
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PDF
Enhancing Security in VAST: Towards Static Vulnerability Scanning
ESUG
 
PPTX
Employee salary prediction using Machine learning Project template.ppt
bhanuk27082004
 
PDF
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
PDF
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
PDF
System Center 2025 vs. 2022; What’s new, what’s next_PDF.pdf
Q-Advise
 
PDF
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
PDF
Virtual Threads in Java: A New Dimension of Scalability and Performance
Tier1 app
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PDF
Troubleshooting Virtual Threads in Java!
Tier1 app
 
PDF
How Agentic AI Networks are Revolutionizing Collaborative AI Ecosystems in 2025
ronakdubey419
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
Enhancing Security in VAST: Towards Static Vulnerability Scanning
ESUG
 
Employee salary prediction using Machine learning Project template.ppt
bhanuk27082004
 
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
System Center 2025 vs. 2022; What’s new, what’s next_PDF.pdf
Q-Advise
 
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
Virtual Threads in Java: A New Dimension of Scalability and Performance
Tier1 app
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Troubleshooting Virtual Threads in Java!
Tier1 app
 
How Agentic AI Networks are Revolutionizing Collaborative AI Ecosystems in 2025
ronakdubey419
 

The Perks and Perils of the Singleton Design Pattern

  • 2. Singleton The Perks and Perils of the Singleton Design Pattern
  • 3. Motivation You have that one, and exactly one object: â—Ź Database connection â—Ź Hardware interface â—Ź … and you have to make sure all parts of the application use that one and only object
  • 4. Solution Head up to that class, and: â—Ź Restrict the class to create only one object â—Ź Provide global access to it Ref: [1]
  • 5. Example Single Instance Global Access Use it anywhere
  • 6. View 1 View 2 Users Store Some object Example - Diagram
  • 7. Example - Even more! View 1 View 2 View 3 Users Store Departments Store Singletons (DB / Backend) Connection
  • 9. Techniques 2 Synchronized lazy initialization Clearer, but lower concurrency Higher concurrency Ref: [2]
  • 10. Techniques - 3 Eager initialization No need for synchronization Ref: [2]
  • 11. Benefits â—Ź State shared globally as required â—Ź Global access; No complications to object access â—Ź The object handles its own creation logic â—Ź Hide details of the Singleton â—Ź Can be used to implement some other patterns as well â—‹ Abstract Factory, Builder, Prototype …
  • 13. Singleton as an anti-pattern Singleton is popular because: â—Ź It was included in GoF Design Patterns â—Ź It’s easy; the easiest in the book People started a rebellion: â—Ź Any design pattern can be abused, except for Singleton â—Ź Valid motive, but ruins everything with its two steps Ref: [3, 10]
  • 14. Glorified Global Variables Have a bug? Now go over all those files for a clue! Mutable state 1 This one caused the bug 2 This one found it Ref: [4]
  • 15. Glorified Global Variables When some code uses a global variable, it’s harder to reason about it Mutable state 1 To know what this object / function is doing 2 You also need to understand what this is doing Ref: [4]
  • 16. Lifecycle The Singleton controls its own creation and lifecycle â—Ź Violation of SRP: â—‹ Connecting to database is a responsibility â—‹ Creating, opening and closing the connection are other responsibilities â—Ź Resetting the state is harder and more error-prone than creating a new object Ref: [3, 5]
  • 17. Lifecycle â—Ź Now you have to make all Singletons reset to initial state â—Ź You have to wait to reset properly â—‹ Sync data â—‹ Clear cache
  • 18. Lifecycle â—Ź The user’s signed-in session is shorter than the application’s lifecycle. â—Ź A global state, if necessary, should only handle states that last for the entire application’s complete lifecycle Ref: [5]
  • 19. Hiding Dependencies â—Ź You don’t know what that Singleton needs â—‹ Singleton.getInstance() doesn’t explain much Data List Singleton What you see Data List Singleton What it actually is Connection Authenticator User Ref: [3]
  • 20. Hiding Dependencies - Example â—Ź Only works when you run as part of the suite. â—Ź When run in isolation, throws NullPointerException. Ref: [3]
  • 21. Hiding Dependencies - Example â—Ź You ask a senior, and he tells you that CreditCardProcessor needs to be handled first â—Ź Still, it throws an exception Ref: [3]
  • 22. Hiding Dependencies - Example â—Ź You ask more. Now you know that both Database and OfflineQueue need to be initialized first â—Ź The code worked! â—Ź Now your bank account only has $12.5 because this code charged you for $100 Must be done in the same order! Ref: [3]
  • 23. â—Ź The code is not stable, if Database gets modified, other classes may fail â—‹ Because you don’t know what depends on Database and how â—Ź The code is not flexible, anything that depends on a Singleton is hard wired to that Singleton â—Ź You can’t unit test a class without the Singleton initialized â—Ź You can’t use mock objects for testing Hiding Dependencies Ref: [3]
  • 24. Encourage Coupling â—Ź Since it’s global, any class anywhere can get it easily â—Ź If the developer is thinking hard how to get it in that class, he would think if that class should get it Coupling between SomeTransaction and MySQLConnection Ref: [4]
  • 25. Encourage Coupling â—Ź Now, you need to use a NoSQL database along with the SQL one â—Ź SomeTransaction should switch to NoSQL database SomeTransaction MongoDBConnection MySQLConnectionTightly coupled Remove the coupling between SomeTransaction and MySQLConnection first
  • 26. Limiting Instantiation Are you really sure you won’t need another object of that Singleton class? nobacks.com SingletonScreen We only need one object for that one screen nobacks.com So what happens when I plug that screen to the laptop?
  • 27. Big deal! I don’t care if they’re bad or not. I only use one or two Singletons, what’s going to happen anyway? Source
  • 28. That’s the real problem! This one or two Singletons are strangling all or most of classes â—‹ Many classes are tightly coupled to it â—‹ Many classes can’t be tested properly â—‹ Change something in that Singleton and all other classes need to be changed as well
  • 29. The Root of the Problem This part is very legitimate! This is not Ref: [9]
  • 30. Solution â—Ź Pass it a.k.a “Inject it!” â—Ź Get it from somewhere already global â—‹ That place is responsible for creating it and managing its lifecycle â—‹ There are some evils that we can only reduce, but can never eliminate, like global state Ref: [7]
  • 31. Example A whole bunch of singletons Ref: [7]
  • 33. Example â—Ź We’re sure that only one object is being used â—Ź Dependencies are declared â—Ź Dependencies are passed â—Ź Each class is testable and mockable â—Ź “Creation” is the factory’s responsibility â—Ź If you ever need to have a new database, you don’t have to modify available classes Ref: [7]
  • 34. Immutable State Singletons Immutable state Singletons, enums in Java, objects in Scala, … are okay But still, be aware of coupling, limiting classes from inheritance, hiding dependencies … Ref: [9]
  • 35. References 1. c2.com: Singleton 2. Wikipedia 3. SO: What's so bad about singletons 4. gameprogrammingpatterns.com 5. Avoiding Singleton Abuse 6. programmers.stackexchange: So singletons are bad then what 7. Singletons are pathological liars 8. Where have all the singletons gone 9. Root cause of singletons 10. Singletons considered stupid