Just to come up with a good reason to go for

public sealed class Singleton
{
    private static Singleton sobjSingleton;

    public static Singleton GetSingleton
    {
        if (sobjSingleton == null)
            sobjSingleton = new Singleton();

        return sobjSingleton;
    }

    private Singleton()
    {
    }
}

instead of the shorter

public sealed class Singleton
{
    public static Singleton TheSingleton = new Singleton();

    private Singleton()
    {
    }
}

The latter uses a public static field: we don't like to use these.

But more important: the first approach creates the singleton instance on
demand. The second approach just creates the instance, even if it isn't
needed throughout the life of an AppDomain. Often singetons are
issued 'heavy' objects: recall the in-memory database mentioned earlier in
this thread. You typically don't want these big things created when you
don't really need them.

P.S. A last note on the sealed modifier that --- appearently --- seems so
natural to us on singleton classes: consider singletons you can inherit
from. Think of cases where you want only one instance for each sub class
to be created.

--Stefan

You can read messages from the Advanced DOTNET archive, unsubscribe from Advanced 
DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to