Tuesday, June 26, 2007

A Singleton thought

Here I am depicting a small and very simple pattern, the most familiar singleton design pattern. when we say singleton it should not create more than one instance at any point of time and there by it should ensure a class has only one instance and provide a global point of access to it.
So, below is an example.

class Singleton
// Static members are lazily initialized.
// .NET guarantees thread safety for static initialization
private static readonly Singleton instance;
// Note: Constructor is 'protected'
protected Singleton()
{ }
public static Singleton Instance()
return instance;

We are giving a protected constructor because the derived classes also should be able to instantiate this, then only they can derive or else if we use a private constructor the derived class will not be able to instantiate their failing in execution. In other words it will indirectly provide or behave as a sealed class, a perfect singleton