Friday, November 21, 2008

Static class, static member and singleton pattern

static class can only have static memebers, and the static class cannot be instantiated.so when we have a class:

public static classA{};

ClassA ca=new ClassA() is not permitted.

static members, such as static field, static constructor, static property, static method, they blong to the class, even this class is not static and the class can be instantiated, these static members are not belong to the instance of this class.

For example, we have a non-static class:

public classB
{

//static field
public static int i;

//static property
private static int j;
public static int J
{
get
{
return j;
}
set
{
value=j;
}
}

//static method
public static void Method()

{
Console.WriteLine(...);
}

}

When we use these members, for example we can have the instance of ClassB
ClassB cb=new ClassB();
And when use these static members, we can only use:

//static field
ClassB.i;

//static property
ClassB.J;

//static method
ClassB.Method();

The following code will guarantee a singleton design pattern:

class Singleton
{
public static readonly Singleton instance=new Singleton();
private Singleton() {}
}

This code have 2 point: the constructor is private, and there only have one instance.

The code is equallent to the following code:

class Singleton
{
public static readonly Singleton instance;

//static constructor, the content is excute before the instance is claimed as static

static Singleton()
{
instance=new Singleton();
}

//private constructor guarantee the constructor are not able to use out side of the class
private Singleton(){}
}

When we use the instance of this class, we can only write as: Singleton.Instance.

No comments: