利用单件模式避免重复打开窗体,窗体为无参数构造函数模式。
注:该博客中有自动关闭窗体的方法
http://www.cnblogs.com/zfanlong1314/p/3567308.html
为了打开窗体时传入参数,可以改变方法的传递参数,本人修改后代码如下
///
<summary>
///
泛型实现窗体实例单件化
///
</summary>
///
<typeparam name="T">窗体类</typeparam>
public static class Singleton<T>
where T : Form//, new()
{
private static T
instance = default(T);
private static readonly object lockHelper = new
object();
///
<summary>
///
获取窗体的唯一实例
///
</summary>
/// <param name="args">构造函数参数</param>
///
<returns></returns>
public static T Instance(object[] args)
{
if (instance == null)
{
lock (lockHelper)
{
if (instance == null)
{
instance =
(T)Activator.CreateInstance(typeof(T), args);
//加上实例关闭事件,窗体就会自动回收,即instance=null;
instance.FormClosed
+= new FormClosedEventHandler(DestroyForm);
}
}
}
return
instance;
}
///
<summary>
///
当窗体关闭时将Instance置空
///
</summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void
DestroyForm(object sender, FormClosedEventArgs e)
{
instance = default(T);
}
这样修改可以避免重复打开窗体,且能传递参数。但是如果一个窗体有多个构造函数时就只能打开一个实例。
搜到如下解决方案,但是对func<T> 方法不熟悉,不知道如何用,待后续研究
http://bbs.csdn.net/topics/360165634
该帖子的最后解决方法是:将你的G_<T>的构造函数中传入一个匿名委托Fun<T>参数,由外部的匿名委托来返回一个对象的实例,这样你就不必关心构造函数是否带参数的情况。代码如下
public class SingletonGenerator<T>
{
private object locker;
private bool initialized =
false;
private Func<T> func;
private T
instance;
public SingletonGenerator(Func<T> funcParam)
{
initialized = false;
func =
funcParam;
locker = new object();
}
public T Value
{
get
{
if (!this.initialized)
{
lock (this.locker)
{
if (!this.initialized)
{
this.instance =
this.func();
this.initialized =
true;
}
}
}
return this.instance;
}
}
}