Alternatives to the Singleton Design Pattern
page 2 of 6
by Steven Smith
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 29036/ 24

The Singleton Pattern

The Singleton pattern works by restricting construction of a class to itself, by making the constructor private.  Then a property (or method) typically called Instance is set up to provide access to the one-and-only-one instance of the class, which is instantiated on the first request.  A UML diagram of the Singleton's structure is shown here:

The code for the naïve implementation of the Singleton pattern follows here.  Do not use this approach in any multi-threaded environment, including an ASP.NET application.

The problem with this implementation is that it is not thread-safe, meaning that the check for (_instance==null) could be executed by two separate threads before either one has instantiated _instance, thus allowing two threads to enter the if {} block and creating two instances of the object.

This issue can be addressed in several ways.  The first is to apply locking, but the simple, brute-force approach to locking doesn't actually work very effectively in terms of efficiency, so as a further optimization one tends to arrive at double-check locking, which works (though not in Java 1.5 or earlier) but is rather complex and very easy to get wrong.

A somewhat simpler approach is to rely on .NET's lazy type instantiation and implement the Instance through the use of a nested class.  This approach is shown here:

Note that the static constructor for Nested() is required, in order to ensure the CLR does not mark the nested type with a flag called beforefieldinit.  You can read more about why this is important in Jon Skeet's excellent article on Singletons, which is where the above LazySingleton pattern comes from.

View Entire Article

User Comments

Title: Just use public static readonly   
Name: Ramon Smits
Date: 2010-12-08 7:42:43 PM
Just use a public static readonly member. Easy, fast, lazy and threadsafe!

public class MyClass
public static readonly MyClass Instance = new MyClass();
private MyClass(){}

Much easier then this will be difficult to do!

Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2024  |  Page Processed at 2024-07-23 2:35:21 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search