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

PPT
Singleton design pattern
PPTX
Singleton Design Pattern - Creation Pattern
PPTX
Design Pattern - Singleton Pattern
PPTX
The Singleton Pattern Presentation
PPT
Introduction to Design Patterns and Singleton
PPTX
Gof design patterns
PPT
Flyweight pattern
PPT
Software Design Patterns
Singleton design pattern
Singleton Design Pattern - Creation Pattern
Design Pattern - Singleton Pattern
The Singleton Pattern Presentation
Introduction to Design Patterns and Singleton
Gof design patterns
Flyweight pattern
Software Design Patterns

What's hot (20)

PPTX
Design pattern (Abstract Factory & Singleton)
PDF
Software Engineering - chp4- design patterns
PPTX
Let us understand design pattern
PPTX
Prototype design patterns
PPTX
Factory Method Pattern
PDF
Design patterns
PPTX
Basic Concepts Of OOPS/OOPS in Java,C++
PPT
Introduction to design patterns
PDF
Selenium Page Object Model Using Page Factory | Selenium Tutorial For Beginne...
PPT
Design patterns ppt
PPT
Class diagrams
PPTX
Proxy Design Pattern
PPTX
04 activities and activity life cycle
PPT
Software Design Patterns
PPT
Design Patterns
PPTX
Design pattern-presentation
PPT
Design Patterns
PDF
Gof design pattern
PDF
UNIFIED MODELING LANGUAGE
PPTX
Windowforms controls c#
Design pattern (Abstract Factory & Singleton)
Software Engineering - chp4- design patterns
Let us understand design pattern
Prototype design patterns
Factory Method Pattern
Design patterns
Basic Concepts Of OOPS/OOPS in Java,C++
Introduction to design patterns
Selenium Page Object Model Using Page Factory | Selenium Tutorial For Beginne...
Design patterns ppt
Class diagrams
Proxy Design Pattern
04 activities and activity life cycle
Software Design Patterns
Design Patterns
Design pattern-presentation
Design Patterns
Gof design pattern
UNIFIED MODELING LANGUAGE
Windowforms controls c#
Ad

Viewers also liked (20)

PDF
Java - Singleton Pattern
PDF
Java8 - Interfaces, evolved
PPTX
The Business of Social Media
PDF
The hottest analysis tools for startups
PPTX
10 Steps of Project Management in Digital Agencies
PDF
Lost in Cultural Translation
PDF
PPTX
All About Beer
PDF
The Minimum Loveable Product
PDF
How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)
PDF
The Seven Deadly Social Media Sins
PDF
Five Killer Ways to Design The Same Slide
PPTX
How People Really Hold and Touch (their Phones)
PDF
Upworthy: 10 Ways To Win The Internets
PDF
What 33 Successful Entrepreneurs Learned From Failure
PDF
Design Your Career 2018
PPTX
Why Content Marketing Fails
PDF
The History of SEO
PDF
How To (Really) Get Into Marketing
PDF
The What If Technique presented by Motivate Design
Java - Singleton Pattern
Java8 - Interfaces, evolved
The Business of Social Media
The hottest analysis tools for startups
10 Steps of Project Management in Digital Agencies
Lost in Cultural Translation
All About Beer
The Minimum Loveable Product
How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)
The Seven Deadly Social Media Sins
Five Killer Ways to Design The Same Slide
How People Really Hold and Touch (their Phones)
Upworthy: 10 Ways To Win The Internets
What 33 Successful Entrepreneurs Learned From Failure
Design Your Career 2018
Why Content Marketing Fails
The History of SEO
How To (Really) Get Into Marketing
The What If Technique presented by Motivate Design
Ad

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

PPS
Singletons
PDF
Robust and Scalable Concurrent Programming: Lesson from the Trenches
PPT
Singleton
PDF
Singleton Sum
PPTX
concurrency_c#_public
PDF
Singleton Pattern
PDF
Design patterns in Java - Monitis 2017
PDF
From Runnable and synchronized To atomically() and parallel()
PPTX
Ahieving Performance C#
PPTX
Concurrency - responsiveness in .NET
PPTX
Quick Interview Preparation for C# All Concepts
PPTX
06.1 .Net memory management
PDF
.Net Threading
PPT
Simple Singleton Java
PPTX
Multi core programming 2
PDF
Top 5 performance problems in .net applications application performance mon...
PPTX
PPT
Introduction To Design Patterns
PPTX
Singleton design pattern
PPTX
Most Useful Design Patterns
Singletons
Robust and Scalable Concurrent Programming: Lesson from the Trenches
Singleton
Singleton Sum
concurrency_c#_public
Singleton Pattern
Design patterns in Java - Monitis 2017
From Runnable and synchronized To atomically() and parallel()
Ahieving Performance C#
Concurrency - responsiveness in .NET
Quick Interview Preparation for C# All Concepts
06.1 .Net memory management
.Net Threading
Simple Singleton Java
Multi core programming 2
Top 5 performance problems in .net applications application performance mon...
Introduction To Design Patterns
Singleton design pattern
Most Useful Design Patterns

More from Sameer Rathoud (8)

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

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
Teaching material agriculture food technology
PPTX
Cloud computing and distributed systems.
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Approach and Philosophy of On baking technology
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Spectroscopy.pptx food analysis technology
PDF
Electronic commerce courselecture one. Pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Big Data Technologies - Introduction.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
KodekX | Application Modernization Development
PDF
Machine learning based COVID-19 study performance prediction
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Chapter 3 Spatial Domain Image Processing.pdf
Teaching material agriculture food technology
Cloud computing and distributed systems.
Diabetes mellitus diagnosis method based random forest with bat algorithm
The Rise and Fall of 3GPP – Time for a Sabbatical?
Approach and Philosophy of On baking technology
Programs and apps: productivity, graphics, security and other tools
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Spectroscopy.pptx food analysis technology
Electronic commerce courselecture one. Pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Big Data Technologies - Introduction.pptx
The AUB Centre for AI in Media Proposal.docx
Network Security Unit 5.pdf for BCA BBA.
Dropbox Q2 2025 Financial Results & Investor Presentation
KodekX | Application Modernization Development
Machine learning based COVID-19 study performance prediction
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

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.