Thursday, April 11, 2013

Generic Singleton C#

Hi Friends,

In my previous thread I discussed about Singleton design pattern with examples.

.NET framework 2.0 has got many new features like Generics, Nullable types, Partial Classes and many more.

Generics are most discussed features of 2.0 framework.

So, now the idea comes that can we have generic singleton class which will return a single object of provided class?

The answer is Yes. We can achieve a generic singleton class using generics.



Here, is how it goes..

class SingletonProvider where T : new() 
{

internal static readonly T instance = new T(); 

public static T Instance 
{

get { return instance; } 
}

static SingletonProvider() { } 


}



Here, I have used static constructor this is to provide both the thread safety as the lazy instantiation.

Test the above SingletonProvider with following programs.



1) Create a one Employee Class.


class Employee

{



string lName; 
string fName;

public String LName 
{

get 
{ 

return lName; 
}

set

{

lName = value; 
}

}



public String FName 
{

get

{

return fName; 
}

set

{

fName = value; 
}

}

public void PrintName() 
{

Console.WriteLine("First Name : " + this.FName + " and Last Name : " + this.LName); 
}

}



Here, I have created an Employee class with two properties LName, FName and one method PrintName().

2) Now, Its time to test SingletonProvider .

I have created following class to test the program.


class TestGenericSingleton

{

static void Main(string[] args) 
{

SingletonProvider.Instance.FName = "James"; SingletonProvider.Instance.LName = "Bond"; 
SingletonProvider.Instance.PrintName();

Console.ReadLine(); 
}

}

The output will be :

First Name : James and Last Name : Bond .

In this way we can create a generic singleton object.

No comments:

Post a Comment

Software Development Blogs - BlogCatalog Blog Directory RSS Search Technology Blogs - Blog Rankings Blog Directory