SlideShare a Scribd company logo
Singleton Pattern
Sole Object with Global Access
Sameer Singh Rathoud
About presentation
This presentation provide information about the various implementation of
singleton design pattern with there pros and cons.

I have tried my best to explain the various implementation in very simple language.
The programming language used for implementation is c#. But any one from
different programming background can easily understand the implementation.
Definition
The singleton pattern is a design pattern that restricts the Instantiation of a
class to one object.
http://en.wikipedia.org/wiki/Singleton_pattern

Singleton pattern is a creational design pattern.
Motivation and Intent
It's important for some classes to have exactly one instance.
e.g.
• Although there can be many printers in a system, there should be only one
printer spooler.
• There should be only one file system and one window manager.
• A digital filter will have one A/D converter.
• An accounting system will be dedicated to serving one company.
• Ensure that only one instance of a class is created.
• Provide a global point of access to the object.
Structure

Singleton
- instance: Singleton
- Singleton();
+ getInstance(): Singleton
Implementation (C#)
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton Instance {
get {
if (instance == null)
instance = new Singleton();
return instance;
}
}
}

When the constructor is defined as a private
method, none of the code outside the class can
create its instances. A static method inside the
class is defined to create an instance on
demand.
In this class, an instance is created only when
static field ‘Singleton.instance’ is ‘null’,
so it does not have the opportunity to get
multiple instances.
This class will works when there is only one
thread, but it has problems when there are
multiple threads in an application. Supposing
that there are two threads concurrently
reaching the if statement to check whether
instance is null. If instance is not created yet,
each thread will create one separately. It
violates the definition of the singleton pattern
when two instances are created. So let’s
explore a thread safe solution.
Thread Safe Implementation
public class Singleton {
private Singleton() {
}
private static readonly object syncObj = new
object();
private static Singleton instance = null;
public static Singleton Instance {
get {
lock (syncObj) {
if (instance == null)
instance = new Singleton();
}
return instance;
}
}
}

Suppose there are two threads that are both
going to create their own instances. As we
know, only one thread can get the lock at a
time. When one thread gets it, the other one
has to wait. The first thread that gets the
lock finds that instance is null, so it creates
an instance. After the first thread releases
the lock, the second thread gets it. Since the
instance was already created by the first
thread, the ‘if’ statement is ‘false’. An
instance will not be recreated again.
Therefore, it guarantees that there is one
instance even if multiple threads executing
concurrently.
This solution will work for multiple
threads, but it is not efficient as every time
‘Singleton.Instance’ get executes, it
has to get and release a lock. Operations to
get and release a lock are timeconsuming, so it should be avoided.
Double-Check Lock
public class Singleton {
private Singleton() {
}
private static object syncObj = new object();
private static Singleton instance = null;
public static Singleton Instance {
get {
if (instance == null) {
lock (syncObj) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}

Actually a lock is needed only before the
only instance is created in order to make
sure that only one thread get the chance to
create an instance. After the instance is
created, no lock is necessary. We can
improve performance with an additional
‘if’ check before the lock.
This Singleton class locks only when
instance is null. When the instance has
been created, it is returned directly
without any locking operations. Therefore,
the time efficiency of this Singleton is
better than its earlier version. Singleton
employs two ‘if’ statements to improve
time efficiency. It is a workable solution,
but a bit complex, and it is error-prone. So
let’s explore the simpler and better
solutions.
Static Constructors
public class Singleton {
private Singleton() {
}
private static Singleton instance = new
Singleton();
public static Singleton Instance {
get {
return instance;
}
}
}

In this Singleton class, an instance is
created when the static field instance gets
initialized. Static fields in C# are initialized
when the static constructor is called. Since
the static constructor is called only once by
the .NET runtime, it is guaranteed that only
one instance is created even in
a
multithreading application. When the .NET
runtime reaches any code of a class for the
first time, it invokes the static constructor
automatically.
Lazy Instantiation
public class Singleton {
Singleton() {
}
public static Singleton Instance {
get {
return InnerClass.instance;
}
}
class InnerClass {
static InnerClass() {
}
internal static readonly Singleton instance
= new Singleton();

}
}

There
is
a
nested
private
class
‘InnerClass’ in this code of Singleton.
When the .NET runtime reaches the code of
the class ‘InnerClass’, its static
constructor is invoked automatically, which
creates an instance of type Singleton. The
class ‘InnerClass’ is used only in the
property ‘Singleton.Instance’. Since
the ‘InnerClass’ class is defined as
private (abstraction), it is inaccessible
outside of the class Singleton.
When
the
get
method
of
‘Singleton.Instance’ is invoked the
first time, it triggers execution of the static
constructor of the class ‘InnerClass’ to
create an instance of Singleton. The
instance is created only when it is
necessary, so it avoids the waste associated
with creating the instance too early.
Examples
• Logger Classes: Logger classes can use this pattern. Providing a global logging access point in
all the application components without being necessary to create an object each time a
logging operations is performed.
• Configuration classes: The classes which provides the configuration settings for an application
can use singleton. By implementing configuration classes as Singleton not only that we
provide a global access point, but we also keep the instance we use as a cache object. When
the class is instantiated( or when a value is read ) the singleton will keep the values in its
internal structure. If the values are read from the database or from files this avoids the
reloading the values each time the configuration parameters are used.
• Accessing resources in the shared mode: The application that work with the serial port can
use this. Let's say that there are many classes in the application, working in an multithreading environment, which needs to operate actions on the serial port. In this case a
singleton with synchronized methods could be used to be used to manage all the operations
on the serial port.

• Abstract factory, builder, prototype, facade can be implemented as singleton.
End of Presentation . . .

More Related Content

What's hot (20)

PPTX
DESIGN PATTERNS: Strategy Patterns
International Institute of Information Technology (I²IT)
 
PPTX
Design Patterns - Abstract Factory Pattern
Mudasir Qazi
 
PPT
Composite pattern
Shakil Ahmed
 
PPTX
Design Pattern - Factory Method Pattern
Mudasir Qazi
 
PPTX
Design pattern (Abstract Factory & Singleton)
paramisoft
 
PPT
Design Pattern
wiradikusuma
 
PPTX
android sqlite
Deepa Rani
 
PPTX
Facade pattern presentation(.pptx)
VishalChavan83
 
PPT
Facade pattern
JAINIK PATEL
 
PPTX
Design pattern - Facade Pattern
Mudasir Qazi
 
PPSX
Observer design pattern
Sara Torkey
 
PPT
Inheritance C#
Raghuveer Guthikonda
 
PPTX
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
PPT
Composite Design Pattern
Ferdous Mahmud Shaon
 
PPT
Basic of Multithreading in JAva
suraj pandey
 
PPTX
07. Virtual Functions
Haresh Jaiswal
 
PPTX
Solid principles
Monica Rodrigues
 
PDF
Java Course 11: Design Patterns
Anton Keks
 
PPSX
Proxy design pattern
Sase Kleckovski
 
PPTX
Python OOPs
Binay Kumar Ray
 
Design Patterns - Abstract Factory Pattern
Mudasir Qazi
 
Composite pattern
Shakil Ahmed
 
Design Pattern - Factory Method Pattern
Mudasir Qazi
 
Design pattern (Abstract Factory & Singleton)
paramisoft
 
Design Pattern
wiradikusuma
 
android sqlite
Deepa Rani
 
Facade pattern presentation(.pptx)
VishalChavan83
 
Facade pattern
JAINIK PATEL
 
Design pattern - Facade Pattern
Mudasir Qazi
 
Observer design pattern
Sara Torkey
 
Inheritance C#
Raghuveer Guthikonda
 
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
Composite Design Pattern
Ferdous Mahmud Shaon
 
Basic of Multithreading in JAva
suraj pandey
 
07. Virtual Functions
Haresh Jaiswal
 
Solid principles
Monica Rodrigues
 
Java Course 11: Design Patterns
Anton Keks
 
Proxy design pattern
Sase Kleckovski
 
Python OOPs
Binay Kumar Ray
 

Viewers also liked (20)

PDF
Java - Singleton Pattern
Charles Casadei
 
PDF
Java8 - Interfaces, evolved
Charles Casadei
 
PPTX
The Business of Social Media
Dave Kerpen
 
PDF
The hottest analysis tools for startups
Liane Siebenhaar
 
PPTX
10 Steps of Project Management in Digital Agencies
Alemsah Ozturk
 
PDF
Lost in Cultural Translation
Vanessa Vela
 
PDF
Flyer
500 Startups
 
PPTX
All About Beer
Ethos3
 
PDF
The Minimum Loveable Product
The Happy Startup School
 
PDF
How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)
Board of Innovation
 
PDF
The Seven Deadly Social Media Sins
XPLAIN
 
PDF
Five Killer Ways to Design The Same Slide
Crispy Presentations
 
PPTX
How People Really Hold and Touch (their Phones)
Steven Hoober
 
PDF
Upworthy: 10 Ways To Win The Internets
Upworthy
 
PDF
What 33 Successful Entrepreneurs Learned From Failure
ReferralCandy
 
PDF
Design Your Career 2018
Slides That Rock
 
PPTX
Why Content Marketing Fails
Rand Fishkin
 
PDF
The History of SEO
HubSpot
 
PDF
How To (Really) Get Into Marketing
Ed Fry
 
PDF
The What If Technique presented by Motivate Design
Motivate Design
 
Java - Singleton Pattern
Charles Casadei
 
Java8 - Interfaces, evolved
Charles Casadei
 
The Business of Social Media
Dave Kerpen
 
The hottest analysis tools for startups
Liane Siebenhaar
 
10 Steps of Project Management in Digital Agencies
Alemsah Ozturk
 
Lost in Cultural Translation
Vanessa Vela
 
All About Beer
Ethos3
 
The Minimum Loveable Product
The Happy Startup School
 
How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)
Board of Innovation
 
The Seven Deadly Social Media Sins
XPLAIN
 
Five Killer Ways to Design The Same Slide
Crispy Presentations
 
How People Really Hold and Touch (their Phones)
Steven Hoober
 
Upworthy: 10 Ways To Win The Internets
Upworthy
 
What 33 Successful Entrepreneurs Learned From Failure
ReferralCandy
 
Design Your Career 2018
Slides That Rock
 
Why Content Marketing Fails
Rand Fishkin
 
The History of SEO
HubSpot
 
How To (Really) Get Into Marketing
Ed Fry
 
The What If Technique presented by Motivate Design
Motivate Design
 
Ad

Similar to Singleton Pattern (Sole Object with Global Access) (20)

PPT
Singleton Object Management
ppd1961
 
PDF
Design patterns in Java - Monitis 2017
Arsen Gasparyan
 
PPTX
Creating and destroying objects
Sandeep Chawla
 
PPT
Singleton
Ming Yuan
 
PPTX
Creational - The Singleton Design Pattern
RagibShahriar8
 
PPTX
Concurrency
Ankur Maheshwari
 
PPS
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla
 
PPT
Jump Start To Ooad And Design Patterns
Lalit Kale
 
PDF
Design patterns in javascript
Ayush Sharma
 
PPT
Simple Singleton Java
Christian Hipolito
 
PPTX
Exploring Kotlin language basics for Android App development
Jayaprakash R
 
PPTX
Threads and synchronization in C# visual programming.pptx
azkamurat
 
PPT
10-design-patterns1.ppt.software engineering
ArwaBohra6
 
PPTX
Sda 8
AmberMughal5
 
PPTX
Meetup - Singleton & DI/IoC
Dusan Zamurovic
 
PPT
Design_Patterns_Dr.CM.ppt
C Meenakshi Meyyappan
 
PPT
04 threads
ambar khetan
 
PDF
OOPs difference faqs- 2
Umar Ali
 
PPTX
PATTERNS02 - Creational Design Patterns
Michael Heron
 
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak
 
Singleton Object Management
ppd1961
 
Design patterns in Java - Monitis 2017
Arsen Gasparyan
 
Creating and destroying objects
Sandeep Chawla
 
Singleton
Ming Yuan
 
Creational - The Singleton Design Pattern
RagibShahriar8
 
Concurrency
Ankur Maheshwari
 
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla
 
Jump Start To Ooad And Design Patterns
Lalit Kale
 
Design patterns in javascript
Ayush Sharma
 
Simple Singleton Java
Christian Hipolito
 
Exploring Kotlin language basics for Android App development
Jayaprakash R
 
Threads and synchronization in C# visual programming.pptx
azkamurat
 
10-design-patterns1.ppt.software engineering
ArwaBohra6
 
Meetup - Singleton & DI/IoC
Dusan Zamurovic
 
Design_Patterns_Dr.CM.ppt
C Meenakshi Meyyappan
 
04 threads
ambar khetan
 
OOPs difference faqs- 2
Umar Ali
 
PATTERNS02 - Creational Design Patterns
Michael Heron
 
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak
 
Ad

More from Sameer Rathoud (8)

PDF
Platformonomics
Sameer Rathoud
 
PDF
AreWePreparedForIoT
Sameer Rathoud
 
PDF
Observer design pattern
Sameer Rathoud
 
PDF
Decorator design pattern (A Gift Wrapper)
Sameer Rathoud
 
PDF
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
PDF
Proxy design pattern (Class Ambassador)
Sameer Rathoud
 
PDF
Builder Design Pattern (Generic Construction -Different Representation)
Sameer Rathoud
 
PDF
Factory method pattern (Virtual Constructor)
Sameer Rathoud
 
Platformonomics
Sameer Rathoud
 
AreWePreparedForIoT
Sameer Rathoud
 
Observer design pattern
Sameer Rathoud
 
Decorator design pattern (A Gift Wrapper)
Sameer Rathoud
 
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
Proxy design pattern (Class Ambassador)
Sameer Rathoud
 
Builder Design Pattern (Generic Construction -Different Representation)
Sameer Rathoud
 
Factory method pattern (Virtual Constructor)
Sameer Rathoud
 

Recently uploaded (20)

PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Market Insight : ETH Dominance Returns
CIFDAQ
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PPTX
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PPTX
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
PDF
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PPTX
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PDF
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Market Insight : ETH Dominance Returns
CIFDAQ
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 

Singleton Pattern (Sole Object with Global Access)

  • 1. Singleton Pattern Sole Object with Global Access Sameer Singh Rathoud
  • 2. About presentation This presentation provide information about the various implementation of singleton design pattern with there pros and cons. I have tried my best to explain the various implementation in very simple language. The programming language used for implementation is c#. But any one from different programming background can easily understand the implementation.
  • 3. Definition The singleton pattern is a design pattern that restricts the Instantiation of a class to one object. http://en.wikipedia.org/wiki/Singleton_pattern Singleton pattern is a creational design pattern.
  • 4. Motivation and Intent It's important for some classes to have exactly one instance. e.g. • Although there can be many printers in a system, there should be only one printer spooler. • There should be only one file system and one window manager. • A digital filter will have one A/D converter. • An accounting system will be dedicated to serving one company. • Ensure that only one instance of a class is created. • Provide a global point of access to the object.
  • 5. Structure Singleton - instance: Singleton - Singleton(); + getInstance(): Singleton
  • 6. Implementation (C#) public class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton Instance { get { if (instance == null) instance = new Singleton(); return instance; } } } When the constructor is defined as a private method, none of the code outside the class can create its instances. A static method inside the class is defined to create an instance on demand. In this class, an instance is created only when static field ‘Singleton.instance’ is ‘null’, so it does not have the opportunity to get multiple instances. This class will works when there is only one thread, but it has problems when there are multiple threads in an application. Supposing that there are two threads concurrently reaching the if statement to check whether instance is null. If instance is not created yet, each thread will create one separately. It violates the definition of the singleton pattern when two instances are created. So let’s explore a thread safe solution.
  • 7. Thread Safe Implementation public class Singleton { private Singleton() { } private static readonly object syncObj = new object(); private static Singleton instance = null; public static Singleton Instance { get { lock (syncObj) { if (instance == null) instance = new Singleton(); } return instance; } } } Suppose there are two threads that are both going to create their own instances. As we know, only one thread can get the lock at a time. When one thread gets it, the other one has to wait. The first thread that gets the lock finds that instance is null, so it creates an instance. After the first thread releases the lock, the second thread gets it. Since the instance was already created by the first thread, the ‘if’ statement is ‘false’. An instance will not be recreated again. Therefore, it guarantees that there is one instance even if multiple threads executing concurrently. This solution will work for multiple threads, but it is not efficient as every time ‘Singleton.Instance’ get executes, it has to get and release a lock. Operations to get and release a lock are timeconsuming, so it should be avoided.
  • 8. Double-Check Lock public class Singleton { private Singleton() { } private static object syncObj = new object(); private static Singleton instance = null; public static Singleton Instance { get { if (instance == null) { lock (syncObj) { if (instance == null) instance = new Singleton(); } } return instance; } } } Actually a lock is needed only before the only instance is created in order to make sure that only one thread get the chance to create an instance. After the instance is created, no lock is necessary. We can improve performance with an additional ‘if’ check before the lock. This Singleton class locks only when instance is null. When the instance has been created, it is returned directly without any locking operations. Therefore, the time efficiency of this Singleton is better than its earlier version. Singleton employs two ‘if’ statements to improve time efficiency. It is a workable solution, but a bit complex, and it is error-prone. So let’s explore the simpler and better solutions.
  • 9. Static Constructors public class Singleton { private Singleton() { } private static Singleton instance = new Singleton(); public static Singleton Instance { get { return instance; } } } In this Singleton class, an instance is created when the static field instance gets initialized. Static fields in C# are initialized when the static constructor is called. Since the static constructor is called only once by the .NET runtime, it is guaranteed that only one instance is created even in a multithreading application. When the .NET runtime reaches any code of a class for the first time, it invokes the static constructor automatically.
  • 10. Lazy Instantiation public class Singleton { Singleton() { } public static Singleton Instance { get { return InnerClass.instance; } } class InnerClass { static InnerClass() { } internal static readonly Singleton instance = new Singleton(); } } There is a nested private class ‘InnerClass’ in this code of Singleton. When the .NET runtime reaches the code of the class ‘InnerClass’, its static constructor is invoked automatically, which creates an instance of type Singleton. The class ‘InnerClass’ is used only in the property ‘Singleton.Instance’. Since the ‘InnerClass’ class is defined as private (abstraction), it is inaccessible outside of the class Singleton. When the get method of ‘Singleton.Instance’ is invoked the first time, it triggers execution of the static constructor of the class ‘InnerClass’ to create an instance of Singleton. The instance is created only when it is necessary, so it avoids the waste associated with creating the instance too early.
  • 11. Examples • Logger Classes: Logger classes can use this pattern. Providing a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed. • Configuration classes: The classes which provides the configuration settings for an application can use singleton. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used. • Accessing resources in the shared mode: The application that work with the serial port can use this. Let's say that there are many classes in the application, working in an multithreading environment, which needs to operate actions on the serial port. In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port. • Abstract factory, builder, prototype, facade can be implemented as singleton.