Introduced
Many people with different development backgrounds are more familiar with the single case pattern. They will find that each time they want to create a different single instance class, they have to write the same code. With the new C # 2.0 generics, you can implement the same code only once.
Using C # 2.0 generics to complete the reuse of a single case pattern
Using the generics of C # 2.0 makes it possible to implement what I call a single instance provider. This is a reusable class that you can use to create a singleton class instance that does not need to override the singleton pattern code for each particular class. This separation of the code from the single case structure will help to keep the class in a single case mode or use the class in a single case mode.
public sealed class Singleton
{
Singleton()
{}
public static Singleton Instance
{
get
{
return SingletonCreator.instance;
}
}
class SingletonCreator
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{}
internal static readonly Singleton instance = new Singleton();
}
}
Based on the understanding of generics, you can see that there is no reason not to replace the type parameter in the code with the typical ' T ' in the generic form. If you do this, the code becomes the following.
public class SingletonProvider<T> where T : new()
{
SingletonProvider() { }
public static T Instance
{
get { return SingletonCreator.instance; }
}
class SingletonCreator
{
static SingletonCreator() { }
internal static readonly T instance = new T();
}
}