DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Design Patterns In C# - Singleton Design Pattern

Richard Mccutchen user avatar by
Richard Mccutchen
·
May. 24, 10 · Interview
Like (0)
Save
Tweet
Share
17.10K Views

Join the DZone community and get the full member experience.

Join For Free

Design patterns are solutions that are used for software development. There are many patterns that are followed, and most companies/developers follow one or more at a time. They range from Abstract Factory (Creating an instance of more than one family of classes) to Singleton (Only a single instance of the class can exist). Today we will be looking at the Singleton Deasign Pattern.

What is it:
The Singleton pattern is a pattern that makes sure that a class only has a single instance, and provides a global access point to it. A class that implements this pattern is itself responsible for keeping track of it's only instance rather than relying on global variables. Many times this pattern is used to hold a part of a system where there can only be a single one. The file system of Windows is a piece like this.

Is It Good Or Bad:
The jury is still out on this one as you have developers who say it should be avoided like the plague, then you have developers who say if the situation fits then go a head and use it, and I fall into that category. Now not every situation in designing an application is right for using the Singleton pattern, but there are real-world situations where it just fits the best.

Let's say you're creating an application that has reporting functionality, and the client wants to maintain a count of all reports that are generated & printed. Since the Singleton design pattern allows for only a single instance, and it a global access point for the reporting module, this would allow you, the designer, to ensure that an accurate count is always maintained, without having to rely on global statics variables.

Introduction & Implementation:
Let's take a look at an implementation of a class using the Singleton design pattern. This example of Singleton takes into account thread-safety by using locking. It takes out a lock on the Singleton class (to ensure no race condition happens) and checks whether an instance already exists. If no instance is founf then it creates an instance, otherwise it returns the instance already available, Locking ensures that one one thread can create an instance.

public sealed class Singleton
{
private static Singleton _classInstance = null;
private static readonly object _threadSafetyLock = new object();

Singleton() { }

public static Singleton Instance
{
get
{
lock (_threadSafetyLock)
{
if (_classInstance == null)
_classInstance = new Singleton();
return _classInstance;
}
}
}
}

A second way of accomplishing and implementing the Singleton design pattern is to use a double-locking technique. This technique solves the concurrency issue, avoiding an exclusive lock whenever the Instance property it called. This approach also allows the developer to delay the instantiation of the object until it is first called upong. Let's take a look at the double-locking technique when implementing the Singleton design pattern:

public sealed class Singleton
{
static volatile Singleton _classInstance = null;
static readonly object _threadSafetyLock = new object();

Singleton() { }

public static Singleton Instance
{
get
{
if (_classInstance == null)
{
lock (_threadSafetyLock)
{
if (_classInstance == null)
_classInstance = new Singleton();
}
}
return _classInstance;
}
}
}



Notice we mark _classInstance property variable as volatile, this ensures that it's value is set before it can be accessed. This ensures that the _classInstance always contains the most current value.

So that is the Singleton Design Pattern, I will be writing a series of articles, looking at several of the most used & popular design patters when developing software so keep your eyes open. Thanks for reading :)

Design

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Keep Your Application Secrets Secret
  • AWS CodeCommit and GitKraken Basics: Essential Skills for Every Developer
  • Getting a Private SSL Certificate Free of Cost
  • The Beauty of Java Optional and Either

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: