Skip to content

The Singleton Pattern: How to make it reusable

November 22, 2008

Always I was bored, when I have to implement The Singleton Pattern in my work, because I have to do it for each class, which must be singleton. That’s why I thought how to improve it and make it reusable for each object, which have to be singleton. I created my implementation of this pattern which is using reflection and generic class.

public abstract class Singleton<T> where T : class

{

private static volatile T _instance;

private static readonly object _locker = new object();

public static T Instance

{

get

{

if (_instance == null)

{

lock (_locker)

{

if (_instance == null)

_instance = Activator.CreateInstance(typeof(T), true) as T;

}

}

return _instance;

}

}

}

The idea of the lines above is so simple. The instance property create our singleton object for the first time if it’s not initialized. I’m instanciate the object using Activator.CreateInsacne method. The important moment here is to use this override, because it’s know that the object that you will instanciate has private constructor. You don’t have to worry about the performance because of a reflection. The reflection is used only one time during the initialization of the singleton object. I’m using this lock statement, because I want this class to be thread safety. Here is the real using of the class:

public sealed class MyClass : Singleton<MyClass>

{

private MyClass()

{

}

}

You have to mark the constructor of your singleton class as private, because you have to protect the class from instantiating the object with it.

It has only one disadvantage. And it’s that if we create our singleton class using as base type my Singleton<T> generic class, your class cannot inherit another class.

From → Articles

2 Comments
  1. C. Popov permalink

    Never use singletons! try to avoid them. In Java we use stuff like managed beans, Lightweight object containers (Spring framework).

    • Svetlin Ralchev permalink

      Don’t say never. It’s not common, but sometimes we need singleton object. I have to check out Spring.NET. Do you talk about dependancy injection containers?

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.