RSS

Implementation Generic Singleton in C#

26 Feb
The last singleton implementation I am going to go over is a generic singleton. This implementation is very similar to the last except that it now uses generics syntax to create a singleton of any class. This does not however prevent the class T from being created by itself. So this implementation has the benefit of being used as is but has the downfall of not being able to force strict control over the singleton.
class GenericSingleton<T> where T : class, new()
{
private static T instance; 

public static T GetInstance()
{
lock (typeof(T))
{
if (instance == null)
{
instance = new T();
}
return instance;
}
}
}

To use this you simply would use a piece of code like below, assuming you have the class AutoFactory defined. AutoFactory’s constructor would also not be able to take parameters in this implementation.

AutoFactory autoF = GenericSingleton<AutoFactory>.GetInstance();

This should give a decent understanding of the singleton pattern and how to implement it using C#. Please post any questions in the comments.

Advertisements
 
Leave a comment

Posted by on February 26, 2011 in Design Pattern

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: