单例模式(singleton)的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。

在多窗体界面中,如果要加入一个“关于”的窗体,用于显示软件的信息,那么可以用到单例模式,因为“关于窗体”类只需一个实例,下面是实例的代码:

"关于窗体":

using System.Windows.Forms;

namespace Keleyi.Com
{
public partial class AboutForm : Form
{
private static AboutForm _instance;

private AboutForm()
{
InitializeComponent();
}

private void AboutForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason== CloseReason.UserClosing)
{
this.Hide();
e.Cancel = true;
}
}

public static AboutForm GetInstance()
{
if (_instance == null)
_instance = new AboutForm();

return _instance;
}
}
}

 

调用代码:

AboutForm m_about;
m_about = AboutForm.GetInstance();
m_about.MdiParent = this;
m_about.Show();

 

 

下载源码:keleyi.codeplex.com


本文转载自柯乐义http://www.keleyi.com/dev/179de6e25d52f044.htm

posted on 2012-11-20 21:11  计划  阅读(3364)  评论(0编辑  收藏  举报