C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Implementing Singleton pattern using Static Constructor and Nested class


Posted Date: 21 Mar 2007    Resource Type: Code Snippets    Category: Design Patterns

Posted By: Prajnan Das       Member Level: Gold
Rating:     Points: 10



Implementation of Singleton pattern may not be that simple when we take into accounts of threading issues. The stereotyped implementation of this pattern is to mark the constructor of the class as private, have a private static field of type of the class itself and a static method which checks for nullity of this variable, and have it created only if it is null. But this may break in a multithreaded environment if two threads simultaneously hit the null condition. We may apply locks to circumvent this issue. But acquiring locks always involves performance overhead. Static constructor and Nested class can provide a novel way of implementing the Singleton pattern.

Presented here is a class called NovelSingleton, which defines a Nested class called Nested private to it. Nested defines a static field called instance of type NovelSingleton and a static constructor which assigns a new instance to the field. NovelSingleton defines a static method getInstance( ) which just accesses and returns the static field of Nested. When a client calls the getInstance( ) method for the first time, the static field of Nested is referenced for the first time and the static constructor gets called. Since it’s a static constructor it is called only once.

using System;

namespace ClassLibrary
{
public class NovelSingleton
{
NovelSingleton() {}

public static NovelSingleton getInstance()
{
Console.WriteLine("Calling getInstance...");
return Nested.instance;
}

public static void boo()
{
Console.WriteLine("boo called!");
}

class Nested
{
static Nested()
{
instance = new NovelSingleton();
Console.WriteLine("instance created!");
}
internal static NovelSingleton instance;
}
}
}

Why we need a nested class here? What is wrong having a static constructor defined for NovelSingleton itself? Because if there is some other static member say boo( ) then the invocation of it before getInstance( ) will trigger the static constructor and we will have an instance created beforehand when it is not required. Here is some quick test code:

NovelSingleton.boo();
NovelSingleton obj1 = NovelSingleton.getInstance();
NovelSingleton obj2 = NovelSingleton.getInstance();
if (obj1 == obj2) Console.WriteLine("they are equal!");

If you run this code you will notice that instance is created only when getInstance( ) is called for the first time.




Responses

Author: Neeraj Saluja    09 May 2008Member Level: Gold   Points : 2
With .NET there are more simpler ways to have the Singleton class, see the simpler implementation below :

public class MySingletonClass
{

private static readonly MySingletonClass _instance = new MySingletonClass();

public static MySingletonClass Instance
{
get
{
return _instance;
}
}



private MySingletonClass()
{
// Have a private constructor so that one cannot create the individual instances of this class
}

//... Other Methods Follows
}


Also, you mentioned that it gets challenging in multi threaded and asynchronous calls environment, but there are simple solutions to it as well. I advice all to look at the lock() method of System.Threading class, it would be really helpful for all.

But Pranjan, no doubt a nice attempt.
Cheers !!!


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Simulation of Synchronized Production and Consumption
Previous Resource: Abstract Factory Design Pattern implementation in C#
Return to Discussion Resource Index
Post New Resource
Category: Design Patterns


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

doors in nj

Contact Us    Privacy Policy    Terms Of Use