Pattern of the Week: Singleton

This is the first in a (hopefully) long series of “Pattern of the Week” posts. I’m primarily sticking with the Gang of Four patterns, but I may branch off occasionally. Thanks for reading.

Type: Creational
Difficulty: Beginner

Singleton. It is probably the least complicated of all design patterns, yet it can be confusing for beginners. In this post, I will attempt to explain exactly how to create a Singleton, talk about common implementation problems, and provide some sample code so you can see it in action.

The basic idea of a Singleton is simple. I only want one of some object. Well, that’s easy, right? Don’t create more than one. Looks like my work here is done. Well, what if I want to ensure that there is only one instance of a certain class ever created while my application is running? That’s where Singleton comes in. Singleton basically protects you from creating more than one of something. It also only creates the instance the first time you use it, i.e., lazy initialization. Here’s a basic implementation:

The above code is pretty much the simplest way to create a Singleton. It also isn’t thread-safe, and it isn’t very useful (no properties, members, etc.). Before we go on to that, let’s explain what we’re looking at. First, you’ll notice that the class has a private constructor. This is due to the fact that we don’t want people to just do this:

You’ll also notice a private, static variable on the class called _instance. This variable is what actually holds the Singleton instance. Finally, you’ll notice the Instance property. This is where all the work is done. The getter first checks to see if there is already an instance, and if there isn’t, it creates one. Then, it simply returns the instance. This ensures that there is only one.

Now, this is great, right? Not really. What if your application is multi-threaded? Meaning, two threads accessing the Instance property at the same time? Well, thread 1 will hit the if statement, and say, “I need to create an instance.” Maybe thread 2 will hit that same if statement before the instance is created, and it’ll say, “I need to create an instance.” So, it’s actually possible to end up with two threads with two different instances of Singleton. Fixing this is simple though. See the below corrected code:

I’ve added a static lock object that will prevent more than one thread from going through the instantiate + return code. This means that if the threads reach the code at around the same time, the later one will have to wait. So, looks like we’ve solved all the problems with Singleton. Wait, what if I create a derived class? You can’t create a derived class outside of the Singleton class, since the constructor is private, but what if you create one inside of Singleton?

Then, somewhere in your code, say:

Guess what? You’ve just created two instances of a Singleton class! How do we fix it? Simple. Add the sealed modifier on to the Singleton class. Sealed classes cannot be derived. Here’s our final code:

To make this useful, you would simply add properties to the Singleton class, then access them like this:

That’s all! Visit next week for an explanation of the Decorator pattern.

View Sample Code

SimpleLookups 1.5.1, Blog Status

Today, I’m releasing SimpleLookups 1.5.1.

This version is a major rewrite of a lot of the core stuff, so it contains no API changes. Basically, if you used it before, it should still work great for you today. The only new thing is that you can now configure it through the app.config/web.config files. The download package contains an example of how to do that, and I’ll be updating the documentation so that it’s even more clear.

You may ask yourself, what happened to 1.5? Well, as of today, SimpleLookups is now available in NuGet. The version had to be revved due to me accidentally pushing an early version of 1.5 during a test, and NuGet not having a way to replace the earlier version (unless the version number is higher). I’m planning to release the next major revision soon anyway, so it’s not a big deal.

Besides the SimpleLookups release, I’m planning to use this site as more of a how-to blog instead of just a release log. I’ve done a couple posts, but I really want to start getting into writing about what I’m learning. The next blog post will be educational, and not a release announcement. Pending bugs of course.

Anyway, keep learning and have a great day. -R

SimpleLookups 1.2 Released

Today, I released SimpleLookups v1.2. This version includes the following changes:

New Features:
– Get a list of lookup values based on a code or a list of codes.
– Remove a list of lookup values based on a code or a list of codes.

Changed Features:
– The methods “GetActive” and “GetAll” are deprecated and are replaced by a single method called “Get”. An activeOnly flag is passed in to the method.

The next release will be v1.5, and it will contain code structure changes and some other changes, namely the ability to configure SimpleLookups through app.config/web.config files.

As typical, a few links for the lazy:
Getting Started with SimpleLookups

Download SimpleLookups 1.2
View Source Code (BitBucket)
View Complete SimpleLookups v1.2 API Documentation

SimpleLookups 1.1 Released

Today, I released SimpleLookups v1.1, which is a small change to the library that is taking the world by storm. (Disclaimer: May not be as popular as advertised.)

This version includes a couple of small API changes, as well as a couple new methods.

New Features:
– Get a list of lookup values based on a list of ids.
– Remove a list of lookup values based on a list of ids.

Changed Features:
– The method “GetById” is now called “Get”.
– The API will now return IList instead of List.

A few links for the lazy:
Getting Started with SimpleLookups

Download SimpleLookups 1.1
View Source Code (BitBucket)
View Complete SimpleLookups v1.1 API Documentation

SimpleLookups 1.0 Released

Today, I released SimpleLookups v1.0, which is a project that I’ve been wanting to release for a long time. This is a small .NET 2.0+ library that is designed to make “lookup” values easy to retrieve from a SQL Server database.

Edit: The tutorial is now here: Tutorial

Download SimpleLookups 1.0
View Source Code (BitBucket)
View Complete SimpleLookups v1.0 API Documentation

SQL Server: Divide Date Range into Months

I wrote a script the other day that is utterly useless to me, but it might be helpful for someone else, so I thought I’d write a quick post about it.

Suppose you have some date range, let’s say “1/20/2013 – 4/29/2014”. Now, suppose you want this range to be broken up into one month sections, with a start and end date for each month. Suppose, for some reason, you want to use a recursive common table expression (CTE). You can just do this:

This would produce the following results:


I think that this is actually pretty cool, but I can’t really come up with a reason to use something like this, outside of maybe a financial application. Anyway, I hope someone gets some use out of it.

Points Calculator 1.1 Released

I just released Points Calculator v1.1 on the “Things I Work On” page. It uses a well-known points-based weight loss formula to calculate how many “points” a particular food is worth. I used to use it in college, and I haven’t really messed with it since then, but I figured I would put it up here in case anyone can use it. It’s also open source if you want to check out how it was made. No real magic there though, just a simple button event and an equation. Anyway, enjoy.

Team Foundation Service: How do I delete a Team Project?

I came across this problem earlier today, and I realized that it isn’t clear how to delete a team project. It is, however, really easy.

All you have to do is open the “Developer Command Prompt for VS2012” (located in Start > All Programs > Microsoft Visual Studio 2012 > Visual Studio Tools) and type the following command (assuming you have the server mapped in Visual Studio).

TfsDeleteProject /force /collection: PROJECT

Replacing the word “ID” with whatever your TFS Online ID is, and “PROJECT” with the name of the team project that you wish to delete.