由于开发一个小Winform小程序,很多页面必须使用单例模式(Singleton Pattern)但由懒的写那么多,所以创建这么一个单例类,诊断窗体进行处理,
此类可以进行作为其他的单例进行使用,只要存在一个父类,那么就可以进行使用。
个人感觉此类书写还比较不错,所以记录以供大家指正、学习。
//单例模式代码 public static class SingletonForm { private static Dictionary<string, Form> _singletonDictionary; public static T GetTInstance<T>(Type claseType) where T :Form, new() { if (_singletonDictionary == null) { _singletonDictionary = new Dictionary<string, Form>(); } //判断是否已经存在指定的窗体 if (_singletonDictionary.ContainsKey(claseType.FullName)) { Form parentForm = _singletonDictionary[claseType.FullName]; //判断是否进行了关闭,因为关闭后会调用Dispose(),导致再次调用的时候会提示无法访问已经释放的资源 if (parentForm.IsDisposed) { _singletonDictionary.Remove(claseType.FullName); parentForm = new T(); _singletonDictionary.Add(claseType.FullName, parentForm); //显示窗体 parentForm.Show(); } //获取焦点 parentForm.Focus(); } else { T tForm = new T(); _singletonDictionary.Add(claseType.FullName, tForm); //显示窗体 tForm.Show(); } return (T)_singletonDictionary[claseType.FullName]; } } //单例模式代码 public static class SingletonForm { private static Dictionary<string, Form> _singletonDictionary; public static T GetTInstance<T>(Type claseType) where T :Form, new() { if (_singletonDictionary == null) { _singletonDictionary = new Dictionary<string, Form>(); } //判断是否已经存在指定的窗体 if (_singletonDictionary.ContainsKey(claseType.FullName)) { Form parentForm = _singletonDictionary[claseType.FullName]; //判断是否进行了关闭,因为关闭后会调用Dispose(),导致再次调用的时候会提示无法访问已经释放的资源 if (parentForm.IsDisposed) { _singletonDictionary.Remove(claseType.FullName); parentForm = new T(); _singletonDictionary.Add(claseType.FullName, parentForm); //显示窗体 parentForm.Show(); } //获取焦点 parentForm.Focus(); } else { T tForm = new T(); _singletonDictionary.Add(claseType.FullName, tForm); //显示窗体 tForm.Show(); } return (T)_singletonDictionary[claseType.FullName]; } }