How can I implement a Singleton class that can be derived from in WPF?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 08:15:02

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/29581635/how-can-i-implement-a-singleton-class-that-can-be-derived-from-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!