I am on the process of creating a generic class for the singleton pattern. My implementation as follows:
public class Singleton<T> where T : new() {
public static T getInstance()
{
if (this_ == null)
this_ = new T();
return this_;
}
private static T this_;
}
Sample use would be:
Singleton<Logger>.getInstance().someMethodHere();
The problem with this implementation is that the target class that would be converted into a singleton must have a public constructor, which is in the first place I am preventing it. I have implemented a simliar approach in C++, however I've used a "friend" class that sould also be declared on the user class. Please advice. Thanks. (BTW, this singleton class would be place on a separate assembly).

Help on creating a generic singleton class
forwheeler
wikipedia
codeproject
Of course it is also not a "true singelton".
TheBlackhorse
Well, it is sort of doing it. The singleton instance is only fetched if you use that generic class to get it. You can create separate instances of the target class by other means, so the approach is not truly a singleton-like... And yeah, the target classes indeed need to have a public constuctor, you cannot create the singleton instance inside the generic class otherwise.
The easier solution is that you just simply apply singleton pattern to all classes you need. It is just few lines of code after all (and you sure won't need huge amounts of singleton classes).
Mantorok
Carl Bateman
public class Singleton<T>
{
private Singleton()
{
}
private static Singleton<T> _instance;
public static Singleton<T> Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton<T>();
}
return _instance;
}
}
public void Print(T parameter)
{
Console.WriteLine(parameter.ToString());
}
}
And some sample usage:
Singleton<int>.Instance.Print(34);
Singleton<string>.Instance.Print("Hello");
Ps. In C# the get and set-methods are not used, they are replaced with Properties (that Instance block with get keyword inside). They are translated to get and set-methods when compiling, so you can use the property even if the .NET language doesen't support Properties.
Pps. The method names are written in Capital letter :)