I have a question, is this the correct approach to make a Generic Singleton?
public class Singleton<T> where T : class, new()
{
private static T instance = null;
private Singleton() { }
public static T Instancia
{
get
{
if (instance == null)
instance = new T();
return instance;
}
}
}
EDIT:
Checking some PDFs I found a generic Singleton made this other way, is this other correct?
public class Singleton<T> where T : class, new()
{
Singleton() { }
class SingletonCreator
{
static SingletonCreator() { }
// Private object instantiated with private constructor
internal static readonly T instance = new T();
}
public static T UniqueInstance
{
get { return SingletonCreator.instance; }
}
}
This how I did it, using the Current pattern (also thread safe initialization)
Usage:
Consume the singleton:
The problem with a generic singleton factory is that since it is generic you do not control the "singleton" type that is instantiated so you can never guarantee that the instance you create will be the only instance in the application.
If a user can provide a type to as a generic type argument then they can also create instances of that type. In other words, you cannot create a generic singleton factory - it undermines the pattern itself.
Note that
Here is my implementation using a non-public constructor. The only issue right now is there is no way to have a custom constraint on C# generics, so I have to throw a run-time exception for derived classes with public default constructors instead of a compile-time error.
You can make a singleton base class using a bit of cheating (reflection). You can (run-time) enforce a class has no public constructor.
this is my point using .NET 4
Usage pattern: