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

Weitere ähnliche Inhalte

Was ist angesagt?

Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
Aman Jain
 
Ch 3 event driven programming
Ch 3 event driven programmingCh 3 event driven programming
Ch 3 event driven programming
Chaffey College
 

Was ist angesagt? (20)

Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 
Ch 3 event driven programming
Ch 3 event driven programmingCh 3 event driven programming
Ch 3 event driven programming
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Solid principles
Solid principlesSolid principles
Solid principles
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 

Andere mochten auch

Five Killer Ways to Design The Same Slide
Five Killer Ways to Design The Same SlideFive Killer Ways to Design The Same Slide
Five Killer Ways to Design The Same Slide
Crispy Presentations
 
Why Content Marketing Fails
Why Content Marketing FailsWhy Content Marketing Fails
Why Content Marketing Fails
Rand Fishkin
 

Andere mochten auch (20)

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

Ähnlich wie Singleton Pattern (Sole Object with Global Access)

Ähnlich wie Singleton Pattern (Sole Object with Global Access) (20)

Singleton Object Management
Singleton Object ManagementSingleton Object Management
Singleton Object Management
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Singleton
SingletonSingleton
Singleton
 
Creational - The Singleton Design Pattern
Creational - The Singleton Design PatternCreational - The Singleton Design Pattern
Creational - The Singleton Design Pattern
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
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
 
Simple Singleton Java
Simple Singleton JavaSimple Singleton Java
Simple Singleton Java
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
Sda 8
Sda   8Sda   8
Sda 8
 
Meetup - Singleton & DI/IoC
Meetup - Singleton & DI/IoCMeetup - Singleton & DI/IoC
Meetup - Singleton & DI/IoC
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
04 threads
04 threads04 threads
04 threads
 
OOPs difference faqs- 2
OOPs difference faqs- 2OOPs difference faqs- 2
OOPs difference faqs- 2
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Singleton class in Java
Singleton class in JavaSingleton class in Java
Singleton class in Java
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 

Mehr von Sameer Rathoud

Mehr von Sameer Rathoud (8)

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

Kürzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

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.