Some time ago I learned of the Singleton implementation that only permits a single instance of a class object by hiding the class initializer and using a private static reference of the object within itself, and a public GETTER that references that private reference -
public class Foo : IDisposable{
private static Foo _Instance;
public static Foo Instance{ get{ return Foo._Instance ?? new Foo(); }
private Foo(){ Foo._Instance = this; }
public void Dispose(){ Foo._Instance = null; }
}
I love this quite a lot - it is especially nice for windows that I want accessible application wide.
One thing that I would really like is to be able to implement a generic sort of Singleton Window class upon which a real window could be built and then accessed like this - Is this possible? My thinking was something like -
public class SingletonWindow : Window {
private static SingletonWindow _Instance;
public static SingletonWindow Instance{ get{ return SingletonWindow._Instance ?? new SingletonWindow(); } }
private SingletonWindow(){ SingletonWindow._Instance = this; }
private sealed override void OnClosed(EventArgs E){ SingletonWindow._Instance = null; }
}
But... something inside me that I can't quite voice tells me that this will absolutely positively fail miserably. Can someone tell me why this would fail (if, indeed it will fail), if it is possible to achieve what I am attempting to achieve here, and how I might go about doing so if it is possible?
Personally, I'm not a fan of singletons. That said, if you want a generic class, make it a generic class. You will have to have a static constructor on your derived class that will provide a route to the private constructor to your generic class, but that's about it.
public abstract class Singleton<T> where T : Window, Singleton<T>
{
protected static Func<T> create;
private static T instance;
public static T Instance { get { return instance ?? (instance = create()); } }
private sealed override void OnClosed(EventArgs e)
{
instance = null;
}
}
public class MyWindow : Singleton<MyWindow>
{
static MyWindow()
{
create = () => new MyWindow();
}
private MyWindow() { }
}
Then you can access the instance on your derived class as if it was a normal singleton.
var myWindow = MyWindow.Instance;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments