asp.net中WinForm使用单例模式示例

例如在Windows应用程序中用下面代码打开一个窗体:

代码如下 复制代码

private void button1_Click(object sender, EventArgs e)

{

(new About()).Show();

}

其结果是每点一次按钮都会打开一个窗体,最后可能是这样:

这显然这我不是我们想要的,正常应该是点击按钮时判断窗体有没有打开过,有打开过显示激活窗体,没有则创建并打开窗体,对代码稍做修改:

代码如下 复制代码

private void button1_Click(object sender, EventArgs e)

{

if (frmAbout == null || frmAbout.IsDisposed)

{

frmAbout = new About();

frmAbout.Show(this);

}

else

{

frmAbout.WindowState = FormWindowState.Normal;

frmAbout.Activate();

}

}

private About frmAbout = null;

这样可以满足上边需求,但是如果有多个地方需要打开窗体,同样的代码就得copy多次,这个场景下,我们可以使用单例模式来解决:

代码如下 复制代码

About.cs:

using System;

using System.Text;

using System.Windows.Forms;

namespace WindowsFormsApplication1

{

public partial (www.111cn.net)class About : Form

{

/// <summary>

/// 不能在外部调用构造函数

/// </summary>

private About()

{

InitializeComponent();

}

/// <summary>

/// 单例模式

/// </summary>

/// <returns></returns>

public static About GetInstance()

{

if (_frmAbout == null || _frmAbout.IsDisposed)

{

_frmAbout = new About();

}

return _frmAbout;

}

private static About _frmAbout = null;

}

}

调用方法:

代码如下 复制代码

private void button1_Click(object sender, EventArgs e)

{

About frmAbout = About.GetInstance();

frmAbout.Show();

frmAbout.WindowState = FormWindowState.Normal;

frmAbout.Activate();

}

from:http://www.111cn.net/net/171/65990.htm