Monday, August 6, 2012

Singleton Design Pattern C# asp .net implement

There are different ways to implement thread safe version like locking, double lock checking and with the help of inner class(lazy instantiations).Because of performance overhead, I always preferred to use lazy instantiations
where you can get the instance from instance property. In my below code

public sealed class threadSafeSingleton{

    private threadSafeSingleton() { }

    public static threadSafeSingleton GetInstance()
    {
        return MyNestedSingletonClass.singleton;
    }

    class MyNestedSingletonClass
    {
        internal static readonly threadSafeSingleton singleton = new threadSafeSingleton();

        static MyNestedSingletonClass() { }
    }
}

internal keyword is used to assign the singleton variable, so that other classes can access it. Nested class make it lazy. So in case if you more static methods in your class you can use them without creating the object.

0 comments:

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Code Imagine